将元素插入MongoDB中的嵌套数组中

时间:2016-03-20 11:21:26

标签: mongodb meteor

我是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"
                         ]
            }
        ]
    }




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

3 个答案:

答案 0 :(得分:12)

这里有两种可能性:

  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)

您可以尝试$addToSet,只有在数组中尚不存在元素时,才会向元素添加元素。

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

答案 2 :(得分:0)

尝试一下:

db.<collection>.updateOne(
   {_id:"iL9hL2hLauoSimtkM",comments:{$elemMatch:{userId:'a3123'}}},
   {$push:{'comments.$.likes':'userID3'}})

$运算符等效于过滤器

$ === {_id:"iL9hL2hLauoSimtkM",comments:{$elemMatch:{userId:'a3123'}}}

不过,我们基本上是将“ userID3”推入

[1]“喜欢”数组
[2]在指定元素内=== $
[3]属于“评论”数组