猫鼬更新子文档数组 [英] Mongoose update array of subdocuments

查看:57
本文介绍了猫鼬更新子文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以更新匹配更新查询的数组中的所有子文档吗?这是集合元素的示例:

Can I update all the subdocuments in array matching my update query? Here is example of collection elements:

{
    x: 1,
    myarray: [
        {
           a: 1,
           b: 2,
        },
        {
           a: 1,
           b: 4,
        }  
    ]
}

然后我这样写查询:

    MyModel.update({x: 1, myarray.a: 1}, 
                   {$set: 
                      {"myarray.$.b": 3}
                   },
                   function(err) {
    });

它仅更新myarray中的 first 子文档.在文档中写道,这种查询仅更新第一个文档.我想知道是否有一种方法可以更新数组中所有匹配的子文档.预先感谢.

It updates only the first subdocument in myarray. In the documentation it is written that this kind of queries update only the first document. I want to know if there is a way to update all matching subdocuments in array. Thanks in advance.

推荐答案

您目前无法使用

You currently can't do that with the positional operator and there is a JIRA for this. However, a workaound is to loop through each matched document and within that document, loop through the array updating the matched element:

db.collection.find({"x": 1, "myarray.a": 1}).forEach(function(doc) {
    doc.myarray.forEach(function(item){
        if(item.a == 1){
            item.b = 3;
        }
    });
    db.collection.save(doc);
});

这篇关于猫鼬更新子文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆