[MongoDB Learning Notes 13] Advanced update operation of MongoDB
I. batch updates
By default, only one document that meets the criteria is updated.
> db.post.find () {"_ id": ObjectId ("54a530c3ff0df3732bac1681"), "id": 2, "name": "joe", "age": 49} {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21, "comments": ["test2", "test9" "test5"]} > db.post.update ({"name": "joe"}, {$set: {"age": 70}}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.find () {"_ id": ObjectId ("54a530c3ff0df3732bac1681"), "id": 2, "name": "joe" "age": 70} {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21, "comments": ["test2", "test9", "test5"]} >
Batch update with the fourth parameter of update:
> db.post.update ({"name": "joe"}, {$set: {"age": 30}, false,true) WriteResult ({"nMatched": 2, "nUpserted": 0, "nModified": 2}) > db.post.find () {"_ id": ObjectId ("54a530c3ff0df3732bac1681"), "id": 2, "name": "joe", "age": 30} {"_ id": ObjectId ("54a530c3ff0df3732bac1680") "id": 1, "name": "joe", "age": 30, "comments": ["test2", "test9", "test5"]} >
Note: update method reference
Update (criteria, objNew, upsert, multi)
Criteria: the query condition of update, similar to the one after where in the sql update query
ObjNew: the object of update and some updated operators (such as $, $inc...), etc., can also be understood as after set in the sql update query
Upsert: this parameter means that whether false or true, a new key is added without a matching key.
Multi: mongodb defaults to false. Only the first record found is updated. If this parameter is true, multiple records found by condition will be updated.
Update the key value of the document, and add the key value if there is no key value.
> db.post.update ({"name": "joe"}, {$set: {"sex": 1}, false,true) WriteResult ({"nMatched": 2, "nUpserted": 0, "nModified": 2}) > db.post.find () {"_ id": ObjectId ("54a530c3ff0df3732bac1681"), "id": 2, "name": "joe", "age": 30 "sex": 1} {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 30, "comments": ["test2", "test9", "test5"], "sex": 1} > db.post.update ({"name": "joe"}, {$set: {"school": "marry"}}, true) True) WriteResult ({"nMatched": 2, "nUpserted": 0, "nModified": 2) > db.post.find () {"_ id": ObjectId ("54a530c3ff0df3732bac1681"), "id": 2, "name": "joe", "age": 30, "sex": 1, "school": "marry"} {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1 Name: "joe", "age": 30, "comments": ["test2", "test9", "test5"], "sex": 1, "school": "marry"} >