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.

1

1 Answer 1

3

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'}]}
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.