[MongoDB learning notes] - use MongoDB for CRUD operation

Author: Huan Hao

Source: Hang Seng LIGHT cloud community

summary

MongoDB is a persistent document oriented database for storing and processing data in the form of documents.

Like other database management systems, MongoDB can manage and interact with data through four basic types of data operations:

  • C: Create an operation that involves writing data to the database
  • R: A read operation that queries the database to retrieve data from it
  • U: Update operation to change the existing data in the database
  • D: Delete operation to permanently delete data from the database

The above four operations are collectively referred to as CRUD operations. This paper mainly explains the principles and commands of these four operations.

Specific operation

Update document

Next, we focus on how to update existing documents by changing field values in a single document and adding new fields to each document in the collection.

Similar to the insertOne() and insertMany() methods, MongoDB provides a way to update a single document or multiple documents at once.

To allow users to perform this operation, MongoDB uses the same query filter document mechanism as the query filter document mechanism for finding and retrieving documents in the update method. Any query filter that can be used to retrieve documents can also be used to specify which documents to update.

updateOne

By changing the name of the Great Wall to the full name of Chuangcheng. To do this, use the updateOne() method that updates a single document:

db.spots.updateOne(
  { "name": "the Great Wall" },
  {
    $set: { "name": "Chuangcheng" }
  }
)

# Output:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

The first parameter of the updateOne method is the query filter document with a single equal condition, as described in the previous step. In this example, {"name": "Great Wall"} looks for a document whose name key is the Great Wall value. Any valid query filter document can be used here.

The second parameter is the update document, which specifies which changes should be applied during the update. The update document consists of the update operator as a key and the parameters of each operator as a value. In this example, the update operator used is $set. It is responsible for setting the document field to the new value and requires a JSON object with the new field value. Here, $set: {"name": "Chuangcheng"} tells MongoDB to set the value of the field name to Chuangcheng.

Then check whether the update is valid:

db.spots.find({"country": "China"}).pretty()

# Output:
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1c"),
        "name" : "Chuangcheng",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 106.384,
                "lng" : 39.031
        }
}
ยทยทยท

updateMany

If you want to modify multiple documents, you can use the updateMany() method.

The following example includes an empty query filter document. By including an empty query document, this operation will match each document in the collection, and the updateMany() method will affect each of them. Update document add a new editor field to each document and assign values to it:

db.spots.updateMany(
  { },
  {
    $set: { "remark": "desc..." }
  }
)

# Output:
{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }

According to the output, all documents are successfully updated, and then verified by printing:

db.spots.find().pretty()

# Output:
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "The Oriental Pearl",
        "country" : "China",
        "city" : "Shanghai",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        },
        "remark" : "desc..."
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "the Imperial Palace",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        },
        "remark" : "desc..."
}
. . .

All returned documents now have a new field named remark set to desc. By providing a nonexistent field name to the $set update operator, the update operation will create the missing field in all matching documents and set the new value correctly.

remove document

If the data in the database does not need to be deleted, like Mongo's update and insert operations, the deleteOne() method only deletes the first document matching the query filter document, and the deleteMany() method deletes multiple objects at a time.

deleteOne

For example, you need to delete a document:

db.spots.deleteOne(
    { "name": "Chuangcheng" }
)

# Output:
{ "acknowledged" : true, "deletedCount" : 1 }

Through the output deletedCount, a document has been deleted successfully, and then print the verification:

> db.spots.find({"country": "China"}).pretty()

# output
{
        "_id" : ObjectId("61b5d4963d2fc20a8483df1a"),
        "name" : "The Oriental Pearl",
        "country" : "China",
        "city" : "Shanghai",
        "location" : {
                "lat" : 121.537,
                "lng" : 31.258
        },
        "remark" : "desc..."
}
{
        "_id" : ObjectId("61b5d7ba3d2fc20a8483df1b"),
        "name" : "the Imperial Palace",
        "city" : "Beijing",
        "country" : "China",
        "gps" : {
                "lat" : 116.403,
                "lng" : 39.924
        },
        "remark" : "desc..."
}

deleteMany

If you need to delete multiple documents at once, you can perform batch filtering and matching deletion through remark. This operation will empty the collection:

 >  db.spots.deleteMany(
      { "remark" : "desc..." }
    )

# Output:
{ "acknowledged" : true, "deletedCount" : 4 }

Verify that the monument collection is now empty by counting the number of documents in it:

> db.spots.count()

# Output:
0

This command returns the expected output 0 because all documents have just been deleted from the collection.

summary

MongoDB provides a powerful query system that allows you to accurately select documents of interest according to complex standards. In the future, we will continue to share in detail the usage skills of MongoDB.

By studying the notes in this article, we can quickly get started with the basic CRUD operation of mongo. Of course, we need to practice by ourselves after learning.

Want to learn more from technology bosses? Where to discuss the problems encountered in development? How to obtain massive financial technology resources?

Hang Seng LIGHT cloud community , the financial technology professional community platform built by Hang Seng electronics shares practical technology dry goods, resource data and financial technology industry trends, and embraces all financial developers.

Scan the QR code of the applet below and join us!

Keywords: Database MongoDB

Added by wafawj on Thu, 23 Dec 2021 06:32:08 +0200