Can MongoDB Update Aggregation Pipeline conditionally replace the document?
Yes it can, you can build the update pipeline in code like you did but you can also do it in Mongo with $cond
like so:
db.collection.updateOne({},
[
{
$replaceRoot: {
newRoot: {
$cond: [
{
$eq: [
"$version",
3
]
},
{
$mergeObjects: [
"$$ROOT",
{
version: 4,
foo: "baz"
}
]
},
"$$ROOT"
]
}
}
}
])
Mongo Playground