0

I am trying to increment all selected items of a subdocument that matches my criteria

My problem is that it only updates the first matching item.

I select my Project(saved as Highlights model) by id. Select all items from subdocument 'highlights', that have an index of greater than given index(variable, passed by request).

in my highlights array i have:

[
    { index: 1, name: "first" },
    { index: 2, name: "second" },
    { index: 3, name: "three" },
    { index: 4, name: "four" }
]

Highlights.update(
  { _id: project, highlights: { $elemMatch: { index: { $gt: index } } } }, 
  { $inc: { "highlights.$.index": -1 } }
)

when i pass the index of 2, i expect following result:

[
    { index: 1, name: "first" },
    { index: 2, name: "second" },
    { index: 2, name: "three" }, 
    { index: 3, name: "four" }
]

but i get this result:

[
    { index: 1, name: "first" },
    { index: 2, name: "second" },
    { index: 2, name: "three" }, 
    { index: 4, name: "four" }
]

any solutions for my intentions?

A. Morales
  • 123
  • 2
  • 19

1 Answers1

0

You can use the positional filter $[<identifier>] with the arrayFilter option to update all the values :

Highlights.update({
    _id: project,
    highlights: { $elemMatch: { index: { $gt: index } } }
}, {
    $inc: { "highligths.$[elem].index": -1 }
}, {
    multi: true,
    arrayFilters: [ { "elem.index": { $gt: index } } ]
});
Nicolas
  • 457
  • 5
  • 15