0

I have the following document

{store : {
        id        : 'STORE1',
        name      : 'Electronics Store',
        locations : [
            {
                id       : 'LOC1',
                quantity : 4
            },
            {
                id       : 'LOC2',
                quantity : 10
            },
            {
                id       : 'LOC3',
                quantity : 5
            }
        ]
    }
}

I want to update the quantity of multiple elements of the locations array based on their id field using $inc.

For example I want to update id : 'LOC1' with +5 to the quantity field and id : LOC3 with +2 to its quantity field.

Is it possible to do this with one query in mongodb instead of using multiple queries for each location.

Fayad
  • 110
  • 11
  • Does this answer your question? [arrayFilters in mongodb](https://stackoverflow.com/questions/51324876/arrayfilters-in-mongodb) --> Making it as direct duplicate, Only change is `$set` to `$inc` – whoami - fakeFaceTrueSoul Jun 04 '20 at 15:43

1 Answers1

2

You can make use of filtered positional operator $[<identifier>]. Below code will be helpful:

db.collection.update(
     {},
     {$inc: {'store.locations.$[elem1].quantity': 5, 'store.locations.$[elem2].quantity': 2}},
     {arrayFilters: [{'elem1.id': 'LOC1'}, {'elem2.id': 'LOC3'}]}
)
ngShravil.py
  • 4,742
  • 3
  • 18
  • 30