简体   繁体   中英

How to set values of nested array of objects in mongodb

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.

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

playground

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM