Home > Mobile >  How to set values of nested array of objects in mongodb
How to set values of nested array of objects in mongodb

Time:08-10

I have a data model which looks like this, so each documents has services array and each service contains an items array and I want to update properties in items array.

{
    services: [
        {
            id: '1',
            name: 'Service 01',
            items: [
                {
                    id: '1',
                    name: '',
                    qty: 10
                },
                {
                    id: '2',
                    name: '',
                    qty: 10
                },
            ]
        },
        {
            id: '2',
            name: 'Service 02',
            items: [
                {
                    id: '3',
                    name: '',
                    qty: 10
                },
                {
                    id: '4',
                    name: '',
                    qty: 10
                },
            ]
        },
    ]
}

I want to set all the quantities inside services -> items to 0, What will be query for doing it I tried to do,

updateMany({}, { $set: { 'services.items.qty': 0 } });

but it's not working. Let me know if you need more details.

CodePudding user response:

the all positional operator $[] operator can be used to update all elements

playground

db.collection.update({},
{
  $set: {
    "services.$[].items.$[].qty": 0
  }
})
  • Related