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

San*_*agi 5 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"
                         ]
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

我想将记录更新为

{
        "_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"
                         ]
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

请提供查询以添加注释中显示的元素.谢谢.

Lua*_*tel 14

两种可能性:

  1. 由于您没有注释的唯一标识符,因此更新comments数组上特定项的唯一方法是显式指示要更新的索引,如下所示:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM"},
      { $push: { "comments.0.likes": "userID3" }}
    );
    
    Run Code Online (Sandbox Code Playgroud)
  2. 如果为注释添加唯一标识符,则可以搜索并更新匹配的项目,而无需担心索引:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM", "comments._id": "id1"},
      { $push: { "comments.$.likes": "userID3" }}
    );
    
    Run Code Online (Sandbox Code Playgroud)