1. One document is as follows
Db.posts.find ()
{ "_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!", "Comments" : []}
2. Insert data into comments _id equals "5388162dfc164ee1f39be37f" in the document
Db.posts.update ({"_id": ObjectId ("5388162dfc164ee1f39be37f")},{$push:{"Comments":{"content":"Good article!","author":"Luxh"}}
Insert One more
Db.posts.update ({"_id": ObjectId ("5388162dfc164ee1f39be37f")},{$push:{"Comments":{"content":"Not bad!","author":"Chuliuxiang"}}})
The results are as follows
Db.posts.find () {"_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!", "Comments" : [ { "content":"Good article!", "author":"Luxh" }, { "content":"Not bad!", "author":"Chuliuxiang" } ]}
3, according to the embedded document query
1) Check out Luxh commented articles
Db.posts.find ({"Comments.author":"Luxh"}) The result is as follows: {"_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!", "Comments" : [ { "content":"Good article!", "author":"Luxh" }, { "content":"Not bad!", "author":"Chuliuxiang" } ]}
2) Query Luxh commented article, return the specified key
Db.posts.find ({"Comments.author":"Luxh"},{"title": 1,"content": 1}) The result is as follows: {"_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!"}
_ID is returned by default. Cancel to set "_id": 0
4. Modification
Modify the content of author=luxh comments to "I like it!"
Db.posts.update ({"Comments.author":"Luxh"},{$set:{"comments.$.content":"I like it!"}}) The result is as follows: {"_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!", "Comments" : [ { "content":"I like it!", "author":"Luxh" }, { "content":"Not bad!", "author":"Chuliuxiang" } ]}
5. Delete
Delete records from AUTHOR=LUXH in comments
Db.posts.update ({},{$pull:{"Comments":{"author":"Luxh"}}) results as follows: {"_id": ObjectId ("5388162dfc164ee1f39be37f"), "title":"Java Example", "content":"This was a example for java!", "Comments" : [ { "content":"Not bad!", "author":"Chuliuxiang" } ]}