Home > database >  Update nested array mongodb
Update nested array mongodb

Time:05-04

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.

CodePudding user response:

You can use all positional operator $[] to update all elements in the array.

db.getSiblingDB("mydatabase").getCollection("stock").updateMany(
  {},
  { $addToSet: { "products.$[].compositions": "color" } }
)

CodePudding user response:

In case of if you don't want to update all elements, you can use arrayFilters (which allows you to use $[i] notation inside option section):
mongodb example playground

db.getSiblingDB("mydatabase").getCollection("stock").updateMany(
  {},
  { $addToSet: { "products.$[i].compositions": "color" } },
  { arrayFilters: [{"i.name": "test12"}]
)
  • Related