Home > Enterprise >  How to update properties of object in array in mongoose
How to update properties of object in array in mongoose

Time:11-04

I've a collection which elements all contain array of objects, I want to update some properties of certain object. There is the collection:

{
    _id:'a45ea2',
    array: [
        {
            _id: '3fa5ce'
            property: 'qwe'
        },
        {
            _id: '5f5f1b'
            property: 'asd'
        },
    ]
}
{
    _id:'cd7114',
    array: [
        {
            _id: '27f580'
            property: 'qwe'
        },
        {
            _id: '2f33dd'
            property: 'asd'
        },
    ]
}

e.g. wanna update obj named _id with property 5f5f1b to property 000000

CodePudding user response:

use update and arrayFilters like this

db.collection.update({},
{
  $set: {
    "array.$[elem].property": "00000"
  }
},
{
  arrayFilters: [
    {
      "elem._id": "5f5f1b"
    }
  ]
})

https://mongoplayground.net/p/OIGVr5HWhr9

  • Related