Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating array of objects with arrayFilters

I am trying to update an array of objects by applying a filter but no updates happen on any of the objects and no errors appear. I would like all objects according to my filter to be updated. I am using MongoDB version 6.0.8.

Query:

Buildings.update({}, {
  $inc: { "floors.$[index]": -1 }
}, {
  arrayFilters: [ { "index": { $gt: 2 } } ]
});

Data:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  _id: "YuzMQ5zKgktzrANsq",
  floors: [
    { index: 0 },
    { index: 1 },
    { index: 2 },
    { index: 3 },
    { index: 4 },
  ]
}

>Solution :

Your arrayFilters and $set operator were incorrect. Since you are trying to update the field in the object, you need the dot notation with $[<identifier>].

db.collection.update({},
{
  $inc: {
    "floors.$[i].index": -1
  }
},
{
  arrayFilters: [
    {
      "i.index": {
        $gt: 2
      }
    }
  ]
})

Demo @ Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading