如何使用arrayFilters更新数组中的元素

时间:2018-10-26 08:21:27

标签: node.js mongodb element

假设文档如下:

{
  "group_id": 1,
  "group_token": "3bu48xp9ok5",
  "group_passward": "0000",
  "admin": "Forne",
  "member": [
    {
      "mid": 1,
      "Name": "Forne",
      "Email": "xxx@xxx.com",
      "Rank": "admin",
      "sub": [
        "test",
        "xxx",
        "Forne"
      ]
    }
  ]
}

这是我的审判:

var collection = myDB.collection('test');
collection.update({"group_token":"3bu48xp9ok5"},{$pull:{"member.$[elem1].sub":"test"}}, {arrayFilters: [{"elem1.Email":"xxx@xxx.com"}],multi: true})

我如何使用“ member.Email”:“ xxx@xxx.com”更新元素,使其成为sub [“ xxx”,“ Forne”]

但它会打印:

  name: 'MongoError',
  message: 'No array filter found for identifier \'elem1\' in path \'member.$[elem1].sub\'',
  driver: true,
  index: 0,
  code: 2,
  errmsg: 'No array filter found for identifier \'elem1\' in path \'member.$[elem1].sub\'' }

如何更新“ sub”:[] ...?

1 个答案:

答案 0 :(得分:1)

您可以将$set$结合使用。

db.getCollection('tests').update({
    "group_token":"3bu48xp9ok5", "member.Email" : "xxx@xxx.com"
},
{
    "$set": {"member.$.sub": ["hhh", "Cat"]}
})

文档之前:

{
    "_id" : ObjectId("5bd2f41ed79cc5d8b1c62972"),
    "group_id" : 1,
    "group_token" : "3bu48xp9ok5",
    "group_passward" : "0000",
    "admin" : "Forne",
    "member" : [ 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "xxx@xxx.com",
            "Rank" : "admin",
            "sub" : [ 
                "test", 
                "xxx", 
                "Forne"
            ]
        }, 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "yyy@yyy.com",
            "Rank" : "admin",
            "sub" : [ 
                "test1", 
                "yyyy", 
                "Forte"
            ]
        }
    ]
}

更新文档后:

{
    "_id" : ObjectId("5bd2f41ed79cc5d8b1c62972"),
    "group_id" : 1,
    "group_token" : "3bu48xp9ok5",
    "group_passward" : "0000",
    "admin" : "Forne",
    "member" : [ 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "xxx@xxx.com",
            "Rank" : "admin",
            "sub" : [ 
                "hhhh", 
                "hhhh", 
                "hhhh"
            ]
        }, 
        {
            "mid" : 1,
            "Name" : "Forne",
            "Email" : "yyy@yyy.com",
            "Rank" : "admin",
            "sub" : [ 
                "test1", 
                "yyyy", 
                "Forte"
            ]
        }
    ]
}