Home > Software engineering >  How update my objects in a document's array in mongoDB
How update my objects in a document's array in mongoDB

Time:10-18

i have the following collection, I have one question about:

{
    "_id" : ObjectId("123456789"),
    "user_id" : 123456,
    "total" : 100,
    "items" : [
            {
                    "item_name" : "my_item_one",
                    "price" : 30
            },
            {
                    "item_name" : "my_item_two",
                    "price" : 30
            },
            {
                    "item_name" : "my_item_three",
                    "price" : 30
            }
    ]
}

how i can update all price concurrently, (price=50 in all objects) thanks for help

CodePudding user response:

You can use positional all operator to update all elements in the array

db.collectionName.update(
   { },
   { $set: { "items.$[].price" : 50 } },
   { multi: true }
)
  • Related