Add, delete and modify operations on mongo documents

    There are many ways to add, delete, and modify documents in mongo db. Here is a brief record of some of the methods I know.

 

Precondition:

        1. Create a study database use study;

        2. Create the persons collection. When inserting data into the persons collection for the first time, it will be automatically created if the collection does not exist. Of course, you can also use the command db.createCollection ("persons", {with some parameters, or without})

        3. db.persons.find({}) can query all documents in the persons collection.

 

1. Adding documents

       ①Add a single document , use save or insertOne or insert method

db.persons.save({"userId":1});
db.persons.insertOne({"userId":2,"name":"huan"});
db.persons.insert({"userId":3,"name":"huan1993",address:["湖北","武汉"]});

      Notice:

              1. save method: If the _id field is passed, if the value of the _id field already exists in the collection, the update operation will be performed.

              2. insertOne method: This method does not support execution plans (官网原文:insertOne() is not compatible with db.collection.explain().Use insert()instead. ).

              3. In the insert method, when the method parameter is {}, it is a single insert.

              4. The insert and insertOne methods will report an error when the value of the _id field is manually specified and the value exists.

 

       ②Increase documents in batches and use the insert or insertMany method.

db.persons.insert([{"userId":4},{"userId":5,"address":["北京"]}]);
db.persons.insertMany([{"userId":6,"name":"1993"},{"userId":7,"name":"19930311"}]);

    Notice:

            1. When the parameter in the insert method is passed as an array, it is batch insertion

            2. If the document in insertMany specifies the _id field, the value of this field must be unique.

            3. insertMany does not support execution plans

            4. By default, if the _id field in insertMany is repeated, the records before the first _id repeat will be inserted successfully, and the subsequent records will fail, even if the number of subsequent records does not have the _id repeat, if I want to The records are also executed, then you need to set ordered to false. That is: db.persons.insertMany([],{ ordered:false })

 

2. Modify the document

      ① Replacement document

      There is a document with userId of 2 above, I want to change the value of name to name-update

    Notice:

            1. If the previous query condition {"userId":2} finds multiple records, only the first record will be updated.

            2. The second method will replace the following documents with the first document that satisfies the condition.

    ② Modify a field in the document

     Note: 1. At this time, update the first record that meets the conditions.

                 2. If the field to be updated does not exist in the original document, this field will be added

    ③ Batch modification

        method one:

        After the above 2 steps, we now have 2 records of {"name":"huan1993"}. Now we need to modify the value of the userId field of the 2 records to 10 at the same time.

   Note:

          1. In the update method, the fourth parameter must be set to true

          2. Batch update can only be used in the modifier of $XXX. When the above $set is deleted, the update will report an error.

    Method two:

        There are 2 records with userId=10 above, but their name values ​​are different, and the bottom is updated to the same.

 

     ④ The save method can also perform the update operation. When the value of _id exists, the update operation will be performed.

         Looking at the picture above, there are 2 records with userId=10. Now we need to update the userId value of the second record to 12, and use the value of the _id field to update.
  

    ⑤ Save or update operation

db.persons.update({"userId":13},{
    $set: {
        "age":25,
        "name": "The first execution will execute the insert operation, so the record cannot be queried at this time, and the second execution will execute the update operation because the record already exists at this time."
    }
},true,false);
db.persons.find({"userId":13});

    Notice:

            1. At this time, the third parameter of update must be set to true, otherwise the insert operation will not be performed when the record cannot be found. The third parameter is upsert

            2. When a record is matched, an update operation will be performed.

 

3. Deletion of documents

       ① Delete all documents

       db.persons.remove({});

       Notice:

           1. db.persons.remove({}) just clears the data in the collection persons, while db.persons.drop() will delete the persons collection.

 

     ② Delete the documents queried according to the conditions

      db.persons.remove({"userId":13});

 

Fourth, the complete script is as follows:

use study;

db.persons.save({"userId":1,"_id":ObjectId("5aa3b4d2ac88ec2a80e6483c")});
db.persons.insertOne({"userId":2,"name":"huan"});
db.persons.insert({"userId":3,"name":"huan1993",address:["湖北","武汉"]});

db.persons.find();

db.persons.insert([{"userId":4},{"userId":5,"address":["北京"]}]);
db.persons.insertMany([{"userId":6,"name":"1993"},{"userId":7,"name":"19930311"}]);

db.persons.update({"userId":2 },{"name":"name-update"});
db.persons.find({"name":"name-update"})

db.persons.update({"name":"name-update"},{$set:{"userId":2,"name":"huan1993"}});
db.persons.find({"userId":2});

db.persons.find({"name":"huan1993"});

db.persons.update({"name":"huan1993"},{ $set: { "userId" : 10} },false,true);
db.persons.find({"name":"huan1993"})

db.persons.updateMany({"userId":10},{$set:{"name":"updateMany"}});
db.persons.find({"userId":10});

db.persons.save({"_id" : ObjectId("5aa3b4dbac88ec2a80e6483d"),"userId":12});
db.persons.find({"userId":12});

db.persons.update({"userId":13},{
    $set: {
        "age":25,
        "name": "The first execution will execute the insert operation, so the record cannot be queried at this time, and the second execution will execute the update operation because the record already exists at this time."
    }
},true,false);
db.persons.find({"userId":13});

db.persons.remove({});
db.persons.remove({"userId":13});
db.persons.drop();

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326169874&siteId=291194637