Mongo:如何将另一个子文档插入现有文档

时间:2013-10-15 01:53:53

标签: mongodb nested documents

我开始学习Mongo。鉴于以下收集,比如称为帖子,我将如何向现有文档插入新评论?我在mongo网站上看到的例子是“简单”的收藏品。谢谢你的帮助。

{ "_id" : ObjectId( "510a3c5382d395b70b000034" ),

  "authorId" : ObjectId( "..." ),
  "comments" : [ 
    { "_id" : ObjectId( "..." ),
      "authorId" : ObjectId( "..." ),
      "content" : "",
      "createdAt" : Date(...) } ],
  "content" : "Some" } 

1 个答案:

答案 0 :(得分:10)

您可以尝试这样的事情:

    db.posts.update({ _id: ObjectId( "510a3c5382d395b70b000034" ) },
    {
     $push: { comments: { "_id" : ObjectId( "..." ),
     "authorId" : ObjectId( "..." ),
     "content" : "",
     "createdAt" : Date(...) } }
    })