2016-03-20 64 views
3

我是mongoDB的新手。我在更新mongoDB集合中的记录方面遇到了一些麻烦。将元素插入MongoDB中的嵌套数组

如何添加元素到数组“喜欢”到嵌入式记录

我有一个嵌入式的收集,如:

{ 
 
     "_id" : "iL9hL2hLauoSimtkM", 
 
     "title" : "Some Topic", 
 
     "followers" : [ 
 
      "userID1", 
 
      "userID2", 
 
      "userID3" 
 
     ], 
 
     "comments" : [ 
 
      { 
 
       "comment" : "Yes Should be....", 
 
       "userId" : "a3123", 
 
       "likes" : [ 
 
          "userID1", 
 
          "userID2" 
 
         ] 
 
      }, 
 
      { 
 
       "comment" : "No Should not be....", 
 
       "userId" : "ahh21", 
 
       "likes" : [ 
 
          "userID1", 
 
          "userID2", 
 
          "userID3" 
 
         ] 
 
      } 
 
     ] 
 
    }

我想更新纪录

{ 
 
     "_id" : "iL9hL2hLauoSimtkM", 
 
     "title" : "Some Topic", 
 
     "followers" : [ 
 
      "userID1", 
 
      "userID2", 
 
      "userID3" 
 
     ], 
 
     "comments" : [ 
 
      { 
 
       "comment" : "Yes Should be....", 
 
       "userId" : "a3123", 
 
       "likes" : [ 
 
          "userID1", 
 
          "userID2", 
 
          "userID3" // How to write query to add this element. 
 
         ] 
 
      }, 
 
      { 
 
       "comment" : "No Should not be....", 
 
       "userId" : "ahh21", 
 
       "likes" : [ 
 
          "userID1", 
 
          "userID2", 
 
          "userID3" 
 
         ] 
 
      } 
 
     ] 
 
    }

请提供查询以添加评论中显示的元素。 谢谢。

回答

8

两种可能性在这里:

  1. 既然你没有对意见的唯一标识符,更新的评论阵列上的特定项目的唯一途径是明确表示要更新的指数,像这样:

    db.documents.update(
        { _id: "iL9hL2hLauoSimtkM"}, 
        { $push: { "comments.0.likes": "userID3" }} 
    ); 
    
  2. 如果您的意见添加一个唯一的标识符,你可以搜索并更新匹配的项目,没有与指数令人担忧:

    db.documents.update(
        { _id: "iL9hL2hLauoSimtkM", "comments._id": "id1"}, 
        { $push: { "comments.$.likes": "userID3" }} 
    ); 
    
+1

谢谢您的重播,查询工作效果很好。 –

+1

真棒!干净和简单的 –

+0

只是想知道是否有可能用一次更新更新多个数组项目?我有一个情况,每个文档最多可以有50个更新。 –

1

您可以尝试$addToSet,只有在数组中尚不存在元素的情况下,才会将元素添加到数组中。

db.topics.update(
    { _id: "iL9hL2hLauoSimtkM" }, 
    { $addToSet: { "comments.0.likes": "userId3" } } 
)