Home > OS >  How to express if-then-else MongoDB aggregation?
How to express if-then-else MongoDB aggregation?

Time:04-24

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?

CodePudding user response:

You can use $ifNull

 {
    $project: {
      full: {
        $ifNull: ["$full", {$concat: ["$first", "_", "$last"]}]
      }
    }
  }

As you can see here

CodePudding user response:

I think you can use $switch as an alternative of if else 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"
        }

  • Related