如何解决MongoDB,如何使用条件更新多个值
我在猫鼬中使用Express
结果将是这样,
考虑初始计数为0
var arr = [0,1,2,3,4,5,6,7,8,9]
{
_id: '1234'
inventory: [
{
itemIndex: 0,count: 3 // increate 3 times,since it included upper array
},{
itemIndex: 1,count: 3 // Increase 3 times this,{
itemIndex: 5,count: 1 // Increase 1,{
itemIndex: 10,count: 0
},{
itemIndex: 11,]
}
**结果应该是
enter code here
我尝试了这段代码,但是我不知道该怎么办。
var filter = { _id: id }
await User.updateOne(filter,{
$inc: {
clubInventories: {
itemIndex: ...... ??
}
}
},
我应该使用updateMany而不是updateOne吗?
请帮助。
解决方法
您可以使用arrayFitlers,
-
elem
是用户定义的标识符,您可以将条件放在数组字段上,并使用$[<identifier>]
位置运算符在更新部分中使用该标识符。
var filter = { _id: id };
var arr = [0,1,2,3,4,5,6,7,8,9];
await User.updateOne(filter,{
$inc: { "inventory.$[elem].count": 1 }
},{
arrayFilters: [
{ "elem.itemIndex": { $in: arr } }
]
}
)
要更新不同索引中的不同计数值,然后使用
var filter = { _id: id };
var arr = [1,9];
var arr1 = [0];
await User.updateOne(filter,{
$inc: {
"inventory.$[elem].count": 1,"inventory.$[elem1].count": 5
}
},{
arrayFilters: [
{ "elem.itemIndex": { $in: arr } },{ "elem1.itemIndex": { $in: arr1 } }
]
}
)