如何在Mongodb中更新/插入Object到内部列表?

L.J*_*J.W 10 concurrency save mongodb

Blog {
   id:"001"
   title:"This is a test blog",
   content:"...."
   comments:[{title:"comment1",content:".."},{title:"comment2",content:"..."}]    
}
Run Code Online (Sandbox Code Playgroud)

评论是博客中的内部列表.

但是我怎样才能只检索comment1?如何在博客中插入/更新新评论?如果我获得完整博客并将内容插入/更新到评论列表中,那么保存完整博客,如何解决并发问题?

谢谢.

Mar*_*ark 22

Blog {  
    id:"001"  
    title:"This is a test blog",  
    content:"...."  
    comments:[{title:"comment1",content:".."},{title:"comment2",content:"..."}]      
}
Run Code Online (Sandbox Code Playgroud)

要插入新评论,请使用$push:

db.blogs.update({id:"001"}, {$push:{comments:{title:"commentX",content:".."}}});  
Run Code Online (Sandbox Code Playgroud)

要更新评论,请使用$set:

db.blogs.update({id:"001"}, {$set :{"comments.2": {...} }});  
db.blogs.update({id:"001"}, {$set :{"comments.2.title": "new title" }});  
Run Code Online (Sandbox Code Playgroud)

2是给定评论的索引.使用引号是必要的.

  • 一个更实际的答案 - 应该被标记为已被接受 (2认同)

shi*_*ara 5

要获取嵌入式文档,您需要获取主文档并在其注释中搜索嵌入文档所需的文档.实际上在MongoDB中没有办法做得更好.

要在嵌入式文档中插入/更新,您可以使用$push$set查询系统来执行此操作.