10
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.

shingara
  • 46,608
  • 11
  • 99
  • 105
L.J.W
  • 1,575
  • 5
  • 18
  • 24

3 Answers3

22
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.

Mark
  • 5,994
  • 5
  • 42
  • 55
  • I have a doubt whith this solution, if 2 different threads, call db.blogs.update at the same time (race condition), Does mongo will ensure the 2 items of the list saved at the document? – landrady Mar 14 '17 at 20:39
5

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.

shingara
  • 46,608
  • 11
  • 99
  • 105
  • Thanks,But I want to get only the comment1,and I need get all the comments?It may issue performance if the comments count is large.. – L.J.W Jan 03 '11 at 09:22
  • you right it's why it's not a good design to use embedded document with some document to grow in time. You need wait the virtual collection to do that in futur – shingara Jan 03 '11 at 09:57
1

To update a specific Comment by title.

db.blogs.update({'comments.title': 'comment1'}, {$set :{"comments.$.title": "new title" }});

You can also update contents of comment with it's title.

db.blogs.update({'comments.title': 'comment1'},  
{$set :{"comments.$.title": "new title", 'comments.$.content': 'this is content' }}); 

If any problem then reply me.

Himanshu
  • 4,327
  • 16
  • 31
  • 39
jatinkumar patel
  • 2,920
  • 21
  • 28