【问题标题】:Update sub document in MongoDB更新 MongoDB 中的子文档
【发布时间】:2010-10-03 15:01:14
【问题描述】:

现在我正在 ASP.NET 中研究 MongoDB,刚刚浏览了一篇文章,其中以博客文章示例并提到了更新 cmets 的以下步骤(子文档)。

  1. 该博客被用作主文档
  2. 评论被视为子文档并与主文档一起发布
  3. 当我们需要向特定博客插入新评论时,我们将获取现有博客文档,在前端添加新评论(子文档)并再次使用博客 ID 更新博客文档。

如果是这样,让我们​​以非常流行的博客场景为例,将数千个 cmets 发布到一个博客。如果要发布任何新评论,我们需要将所有现有的 cmets 从 DB 服务器获取到 Web 服务器,这样会增加网络流量。

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

【问题讨论】:

    标签: mongodb document


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      有一个 $push 运算符用于将指定的值附加到数组中。假设我们有以下博客文章模式。帖子中已经有两个 cmets,如果您想在帖子中添加其他评论,可以使用 $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 的详细信息

      【讨论】:

        猜你喜欢
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 2016-06-17
        • 2016-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多