I have a document like this
{
"_id": ObjectId("626f942bb092f78afd9dad9d"),
"item_id": "external _id222",
"metadata": {
"item_name": "abc",
"quantity": 123,
"state": null
},
}
What I would like to do is, $inc
i.e. increment the count of quantity
and then update the state
to SOLD, if quantity
equals 124. I can do this by 2 queries, update quantity
, do an if-else check and then update state
. Is there a way to do this in one single query by update()
? (preferably without aggregation)
2
Answers
You can do this way
quantity
is 123quantity
andset
state toSOLD
playground
Here, the trick is that you need to check the value which is before
$inc
operation.With MongoDB v4.2+, you can do this with a single update with an aggregation pipeline to achieve atomic behaviour. Use
$add
to do the increment and$cond
to check for quantity = 123Here is the Mongo playground for your reference.