Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update/insert Object into inner List in Mongodb?

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.

like image 204
L.J.W Avatar asked Jan 03 '11 04:01

L.J.W


People also ask

How do I update a nested array in MongoDB?

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.

How do you update an array object in MongoDB?

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.

How do you update one property in MongoDB?

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.


2 Answers

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.

like image 148
Mark Avatar answered Oct 26 '22 10:10

Mark


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.

like image 35
shingara Avatar answered Oct 26 '22 09:10

shingara