MongoDB更新数组内部的数组中的对象

时间:2020-07-21 14:46:11

标签: mongodb mongodb-query

我正在尝试从嵌套在数组中的数组中的对象更新字段上的数量。而且我无法确定要执行的查询。

我可以更新一个数组内对象的字段。但是当我尝试下降一个级别时,会得到“查询中的美元太多”

这是文档。如何将红酒的数量从3增加到5?例如

{
    "_id" : "bTTALd6kuBfEqFEiW",
    "charges" : [ 
        {
            "_id" : "0",
            "type" : "charge",
            "selected" : "tab-unselected",
            "concept" : "booking",
            "items" : [ 
                {
                    "_id" : "rGmt5wLuLN6MyW3og",
                    "item" : "red Wine",
                    "quantity" : 3,
                    "price" : 280
                },
{
                    "_id" : "rGmt5gwLuLN6MyW3o",
                    "item" : "white Wine",
                    "quantity" : 3,
                    "price" : 280
                }
            ]
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

看看documentation中的位置运算符$[]arrayFilters

const query = {
  _id: "bTTALd6kuBfEqFEiW"
};

const update = {
  $set: { "charges.$[charge].items.$[item].quantity": 5 }
};

const options = {
  arrayFilters: [ { "charge._id": "0" }, { "item._id": "rGmt5wLuLN6MyW3og" } ]
};

db.test.update(query, update, options);

相关问题