猫鼬递增另一个子文档数组中的子文档数组值



我有这样的文档

_id:'111'
products:[
{
_id:'pqr'
nums:[
{_id:'aaa',
quantity:50
},
{_id:'bbb',
quantity:50
}
]
}
]

为了便于理解,上面的文档可以这样总结。

_id
products: [
nums: [
{}, //quantity is in this object
{}
]
]

我需要根据其_id递增产品子文档中的 nums 子文档中的数量值

这是我到目前为止尝试过的,但它不起作用,因为我不知道如何捕获 nums 对象中的_id以更新该子文档数组中的特定对象。

Shop.findOneAndUpdate(
{ "_id": '111', "products._id": 'pqr'  },
{
"$inc": {
"products.$[].nums.quantity": 1
}
}
)

我怎样才能做到这一点?

在更新操作中使用数组过滤器:

db.getCollection("collectionName").findOneAndUpdate(
{ _id: "111" }, // Querying against `_id`, need to convert string to `ObjectId()` or instead use `.findByIdAndUpdate()`
{ $inc: { "products.$[p].nums.$[n].quantity": 1 } },
{
arrayFilters: [{ "p._id": "pqr" }, { "n._id": "aaa" }] // Inputs here
}
// Use { new : true } Option in mongoose to return updated document
);

输入文档 :

{
"_id" : "111",
"products" : [ 
{
"_id" : "pqr",
"nums" : [ 
{
"_id" : "aaa",
"quantity" : 50
}, 
{
"_id" : "bbb",
"quantity" : 50
}
]
}, 
{
"_id" : "abc",
"nums" : [ 
{
"_id" : "aaa1",
"quantity" : 501
}, 
{
"_id" : "bbb1",
"quantity" : 501
}
]
}
]
}

输出文档 :

{
"_id" : "111",
"products" : [ 
{
"_id" : "pqr",
"nums" : [ 
{
"_id" : "aaa",
"quantity" : 51 // This got incremented
}, 
{
"_id" : "bbb",
"quantity" : 50
}
]
}, 
{
"_id" : "abc",
"nums" : [ 
{
"_id" : "aaa1",
"quantity" : 501
}, 
{
"_id" : "bbb1",
"quantity" : 501
}
]
}
]
}

参考 :猫鼬的 .findByIdAndUpdate((

最新更新