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)
CodePudding user response:
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 = 123
db.collection.update({
"item_id": "external _id222"
},
[
{
$set: {
"metadata.quantity": {
$add: [
"$metadata.quantity",
1
]
}
}
},
{
$set: {
"metadata.state": {
$cond: {
if: {
$eq: [
"$metadata.quantity",
124
]
},
then: "SOLID",
else: "$metadata.state"
}
}
}
}
],
{
multi: true
})
Here is the Mongo playground for your reference.
CodePudding user response:
You can do this way
- Check if
quantityis 123 - Then increment
quantityandsetstate toSOLD
db.collection.update({
"metadata.quantity": 123
},
{
"$inc": {
"metadata.quantity": 1
},
"$set": {
"metadata.state": "SOLD"
}
},
{
"multi": false,
"upsert": false
})
Here, the trick is that you need to check the value which is before $inc operation.
