skip to Main Content

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


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

    db.getSiblingDB("mydatabase").getCollection("stock").updateMany(
      {},
      { $addToSet: { "products.$[].compositions": "color" } }
    )
    
    Login or Signup to reply.
  2. 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"}]
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search