A2ub
A2ub

Reputation: 434

How to update an array of documents with an array of values in mongoDB?

I have a collection of Product, the client post and Order request with an array of objects every single object contains the _id product (objectId) and the quantity he bought.

[
{producId: "dshsdsdh72382377923",
quantity: 20
},
{producId: "dsh673sdh72382377923",
quantity: 10
},
{producId: "hjddjkdjkdj676372373",
quantity: 5
},
]

I want to query the Product Collection and decrement (Update) the numberInStock of every product with the quantity that the client bought ! How can i do it ?

Upvotes: 0

Views: 35

Answers (1)

Mohammad Basit
Mohammad Basit

Reputation: 575

Build dynamic query based on how many items user purchased. Select the product by it's productId and decrement the quantity by customerValue

let customerValue = 4; // Let's say the customer bought 4 items
let query = {};
query['quantity'] = -customerValue;
db.collection.updateOne(
 {producId : "hjddjkdjkdj676372373"},
 {$inc: query}
);

Upvotes: 1

Related Questions