'How to express if-then-else MongoDB aggregation?
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?
Solution 1:[1]
You can use $ifNull
{
$project: {
full: {
$ifNull: ["$full", {$concat: ["$first", "_", "$last"]}]
}
}
}
As you can see here
Solution 2:[2]
I think you can use $switch as an alternative to if, else and then. It will help to write series of cases.
You can check out this demo working code in this link: https://mongoplayground.net/p/nUM2DRkNbdY
$switch: {
branches: [
{
case: {
$or: [
{
$lt: [
"$full",
null
]
},
{
$eq: [
"$full",
null
]
}
],
},
then: {
"$concat": [
"$first",
"_",
"$last"
]
}
}
],
default: "$full"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Gabriel Scavassa |
