[MongoDB Learning Notes 8] in-depth MongoDB update (update) operation: modifier $set
After the MongoDB document is stored in the database, the update method is used to update the document. The update method has two parameters, such as
Update (args1,args2)
Args1 refers to the conditions for querying documents.
Args2 refers to what kind of changes are made to the documents queried.
I. document replacement
> joe1= db.post.findOne ({"age": 20}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 20} > joe1.age=2121 > db.post.update ({"nMatched": 1}, joe1) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) >
The modified result:
> joe1= db.post.findOne ({"age": 21}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21} >
Second, use modifiers
1.$set modifier
$set is used to specify the value of a field and create it if the field does not exist.
> db.post.findOne () {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0, "name": "joe", "age": 65}
Add the key to comments:
> db.post.update ({"id": 0},... {$set: {"comments": "i love you"}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne () {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0, "name": "joe" "age": 65, "comments": "i love you"} >
Modify the value of the comments key:
> db.post.update ({"id": 0}, {$set: {"comments": "i don't love you"}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne () {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0, "name": "joe" "age": 65, "comments": "i don't love you"} >
Change the value of comments to an array:
> db.post.update ({"id": 0}, {$set: {"comments": ["i love you", "or", "i don't love you"]}}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 0}) {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0 "name": "joe", "age": 65, "comments": ["i love you", "or", "i don't love you"]} >
Delete the value of comments:
> db.post.update ({"id": 0}, {$unset: {"comments": 1}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 0}) {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0, "name": "joe" "age": 65} >
two。 Modify embedded document
> db.post.findOne ({"id": 0}) {"_ id": ObjectId ("54a530c3ff0df3732bac167f"), "id": 0, "name": "joe", "age": 65, "comments": {"1": 1, "2": 2 "3": 3}} > db.post.update ({"id": 0}, {$set: {"comments.1": 4}}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 0}) {"_ id": ObjectId ("54a530c3ff0df3732bac167f") Id: 0, name: joe, age: 65, comments: {"1": 4, "2": 2, "3": 3}} >