在MongoDB中更新子文档

时间:2010-10-03 15:01:15

标签: mongodb document

现在我正在使用ASP.NET中的MongoDB,刚刚阅读了一篇文章,其中有一篇博客文章示例,并提到了以下步骤来更新评论(子文档)。

  1. 博客被拍成主要文件
  2. 评论被视为子文档并与主文档一起发布
  3. 当我们需要向特定博客插入新评论时,我们将获取现有博客文档,在前端添加新评论(子文档)并再次使用博客ID更新博客文档。
  4. 如果是这种情况,让我们采取非常受欢迎的博客方案,其中有数千条评论发布到博客。如果必须发布任何新评论,我们需要将所有现有评论从数据库服务器获取到Web服务器,因此会增加网络流量。

    这是一般情况还是有其他方法可以将新内容添加到子文档?意思是,我需要一个只应在现有文档中插入新值的功能。

2 个答案:

答案 0 :(得分:0)

MongoDB支持“推送”命令。 push command会将项目附加到现有数组。

答案 1 :(得分:0)

有一个 $ push 运算符,用于将指定的值附加到数组中。假设我们有博客文章的以下架构。帖子中已经有两条评论,如果您想在帖子中添加其他评论,可以使用$ push运算符。我编写了一个示例代码,用于在节点中向下面的模式插入注释,但您也可以在任何.NET中使用该逻辑

{ "_id" : ObjectId("55d58d05471d5cc42aaaef1b"), "title" : "How to drop a collection in MongoDB?", "author" : "dp123", "body" : "body part goes ........!!!", "permalink" : "How_to_drop_a_collection_in_MongoDB", "tags" : [ "MongoDB", "Mongod", "mongo" ], "comments" : [ { "author" : "DP", "body" : "awesome ......", "email" : "dp@tektak.com" }, { "author" : "John", "body" : "This article is really useful for me. I am not getting solution since last few week but finally I got it. Thank you very much!!!", "email" : "john@gmail.com" } ], "date" : ISODate("2015-08-20T08:17:09.541Z") }

 **The code snippet is given below:**





   var comment = {'author': name, 'body': body};
   if (email != "") {
        comment['email'] = email;
    }

   var query ={'permalink': permalink};
   var operation ={'$push':{'comments': comment}};
   db.collection('posts').update(query, operation, function (err, updated){
        console.log("Successfully added the comment!!!");            
  });

我们可以在http://docs.mongodb.org/manual/reference/operator/update/push/

详细了解$ push
相关问题