Say we have a collection with this document structure
{
"full": <string>,
"first": <string>,
"last": <string>
}
Looking for an expression in $project
with the following logic
if ("$full" is null or absent)
concatenate ("$first", "_" , "$last")
else
"$full"
I have managed to write this, but it does not work properly for some cases and looks huge
$project: {
"fullName": {
$cond: {
if: { "$full": null },
then: { $concat: [ "$first", "_", "$last" ] },
else: "$full"
}
}
}
What is a concise way to express this intention in MongoDB aggregation?
2
Answers
You can use
$ifNull
As you can see here
I think you can use
$switch
as an alternative toif
,else
andthen
. It will help to write series of cases.You can check out this demo working code in this link: https://mongoplayground.net/p/nUM2DRkNbdY