0

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:

{
  _id: "YuzMQ5zKgktzrANsq",
  floors: [
    { index: 0 },
    { index: 1 },
    { index: 2 },
    { index: 3 },
    { index: 4 },
  ]
}
Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Gravity123
  • 1,130
  • 3
  • 21
  • 39

1 Answers1

1

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46