Blog {
id:"001"
title:"This is a test blog",
content:"...."
comments:[{title:"comment1",content:".."},{title:"comment2",content:"..."}]
}
comments is a inner list in blog.
But how can I retrieve only comment1? and How can I insert/update a new comment into the blog?if I get a full blog and insert/update the content into comments List,then save the full blog,how to solve concurrent isuue?
Thanks.
Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.
MongoDB Update a Specific Fields To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.
Blog {
id:"001"
title:"This is a test blog",
content:"...."
comments:[{title:"comment1",content:".."},{title:"comment2",content:"..."}]
}
To insert new comment, use $push
:
db.blogs.update({id:"001"}, {$push:{comments:{title:"commentX",content:".."}}});
To update a comment, use $set
:
db.blogs.update({id:"001"}, {$set :{"comments.2": {...} }});
db.blogs.update({id:"001"}, {$set :{"comments.2.title": "new title" }});
2 is the index of the given comment. Usage of quote mark is necessary.
To fetch the embedded document you need fetch the master document and search on his comments embedded document the document you want. There are no way to do better in MongoDB actually.
To insert/update in a embedded document you can use the $push
and $set
query system to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With