skip to Main Content

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


  1. You can use $ifNull

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

    As you can see here

    Login or Signup to reply.
  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"
            }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search