Reputation: 1377
I have a collection of documents that looks like this:
[
{"_id":ObjectId('602a7a9ac0bf9d23c67a41ba'),
'brand':'horn',
'products':[
{'type':'red','ticks':0,'name':'model 1'},
{'type':'green','ticks':0,'name':'model 2'},
{'type':'red','ticks':0,'name':'model 3'},
]
},
{"_id":ObjectId('602a7a9ac0bf9d23c67a1234'),
'brand':'leg',
'products':[
{'type':'red','ticks':0,'name':'model 1'},
]
},
]
I would like to update all documents with the brand:horn
and increment all products with not the type:red
by 1. I am currently querying this way:
coll.updateMany({ "brand": "horn", "products.type": { $ne: "red" } }, { $inc: { "products.$.ticks": 1 } }, { 'multi': true })
However this is not working. How can I perform this update properly?
Upvotes: 0
Views: 47
Reputation: 721
You have the part for the array filter "products.type": { $ne: "red" }
in the wrong place.
It should be written in option arrayFilters
.
Your update should look like this:
coll.updateMany({ "brand": "horn"}, { $inc: { "products.$[element].ticks": 1 } }, { 'multi': true, arrayFilters: [{"element.type": { $ne: "red" }}]});
In addition to the answer your query:
{ "brand": "horn", "products.type": { $ne: "red" } }
Will return empty result, since your document with brand=horn
has at least one product where type=red
Upvotes: 1