How to Update a field by reading the old value from the document then update a new value to that field in MongoDB.
suppose in a document i have a field named Qty and it already has a value like Qty = 2; now i need to update the Qty = 5; So after update i need the Qty be 2 5 = 7; no directly replace 2 with 5. please help me.
CodePudding user response:
Suppose you have a model like below.
db.products.insertOne(
{
_id: 1,
sku: "foo",
quantity: 2,
}
)
The following updateOne() operation uses the $inc operator to:
- increase the quantity field by 2
db.products.updateOne(
{ sku: "foo" },
{ $inc: { quantity: 2 } }
)