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 },
]
}
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
}
}
]
})