chandan kumar
chandan kumar

Reputation: 83

$inc with multiple conditions and different update values in mongoDB

I have a Products collection with data as given below. I am stuck with the requirement to write a single update query to decrease the stock of pId 1 by 2 and pId 2 by 3.

{
    "category":"electronics",
    "products":[
        {
            "pId":1,
            "stock":20
        },
        {
            "pId":2,
            "stock":50
        },
        {
            "pId":3,
            "stock":40
        }
    ]
}

Upvotes: 1

Views: 29

Answers (1)

mickl
mickl

Reputation: 49945

You need the filtered positional operator to define array elements matching conditions separately:

db.col.update(
    { category: "electronics" }, 
    { $inc: { "products.$[p1].stock": -2, "products.$[p2].stock": -3 } },
    { arrayFilters: [ { "p1.pId": 1 }, { "p2.pId": 2 } ] }
)

Upvotes: 1

Related Questions