I want do an updateMany() operation on a nested array for all documents of my collection.
Here is the documents format :
{
"number": 1,
"products": [{
"name": "test",
"compositions": ["water", "sugar"],
}]
},
{
"number": 2,
"products": [{
"name": "test12",
"compositions": ["cotton", "linen"],
}]
}
How can add element ("color" for example) in compositions array nested in product array for all documents by doing updateMany() operation ?
I try this but it is not work :
db.getSiblingDB("mydatabase").getCollection("stock").find().forEach(element => {
element.products.forEach(product => {
db.stock.updateOne(
{$set: {
'compositions': { $addToSet: { 'product.compositions' : "color"}}
}})
})
})
Thank you in advance.
2
Answers
You can use all positional operator
$[]
to update all elements in the array.In case of if you don’t want to update all elements, you can use
arrayFilters
(which allows you to use$[i]
notation insideoption
section):mongodb example playground