[MongoDB Learning Notes 12] in-depth MongoDB update (update) operation: array modification
View a document whose key value comments is an array ["test1", "test2"]:
> db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21, "comments": ["test1", "test2"]} >
1. $push adds elements to the end of the array
> db.post.update ({"id": 1}, {$push: {"comments": "test3"}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21 "comments": ["test1", "test2", "test3"]} >
Use $each to add multiple values at once:
> db.post.update ({"id": 1}, {$push: {"comments": {$each: ["test4", "test5", "test6"]}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1 "name": "joe", "age": 21, "comments": ["test1", "test2", "test3", "test4", "test5", "test6"]} >
Delete the elements in the array with $pop
Delete a value from the end of the array:
> db.post.update ({"id": 1}, {$pop: {"comments": 1}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21 "comments": ["test1", "test2", "test3", "test4", "test5"]}
Remove a value from the beginning of the array:
> db.post.update ({"id": 1}, {$pop: {"comments":-1}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21 "comments": ["test2", "test3", "test4", "test5"]} >
Delete a specified value in the array:
> db.post.update ({"id": 1}, {$pull: {"comments": "test3"}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe", "age": 21 "comments": ["test2", "test4", "test5"]} >
4. Modify based on the position of array subscript:
> db.post.update ({"id": 1}, {$set: {"comments.1": "test9"}) WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1}) > db.post.findOne ({"id": 1}) {"_ id": ObjectId ("54a530c3ff0df3732bac1680"), "id": 1, "name": "joe" "age": 21, "comments": ["test2", "test9", "test5"]} >