I would Like to make sure some condition is met before performing an update operation.
Is this possible with MongoDB in a single query?
For example, I have the following collection A:
{"_id":"1", "content":{"a":1, "b":2}},
{"_id":"2", "content":{"a":1, "b":2}},
I would like to perform an update on a document where "_id" is "1", only if there is no document that has "_id":"2" in this entire collection A.
CodePudding user response:
You can use a $lookup
to check for the existence of doc _id:"2"
. After that, based on the $lookup
result to perform $merge
to update back to doc _id:"1"
.
db.collection.aggregate([
{
$match: {
_id: "1"
}
},
{
"$lookup": {
"from": "collection",
"let": {
docId: "2"
},
"pipeline": [
{
$match: {
$expr: {
$eq: [
"$_id",
"$$docId"
]
}
}
}
],
"as": "doc2"
}
},
{
$match: {
doc2: []
}
},
{
$addFields: {
someNewFields: "..."
}
},
{
$project: {
doc2: false
}
},
{
"$merge": {
"into": "collection",
"on": "_id",
"whenMatched": "replace"
}
}
])
Here is the Mongo playground that doc _id:"2"
exists.
Here is the Mongo playground that doc _id:"2"
does not exist.