Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoose return default value instead of null value

I have a collection with a fields for the first name and the last name that are optional and can be not set at all.

However I need to query the concatenation of them to search for a full name, but if one of the names isn't set then the return value of the concatenation is null.

Is there a way to return/concat a default value (an empty string) in case the name is not set?

I want to do something like:

db.User.aggregate([
  {
    $project: { firstName: '$firstName' || '' },
    $project: { lastName: '$lastName' || '' },
    $project: { fullName: { $concat: ['$firstName', ' ', '$lastName'] } }
  }
]);

or even:

db.User.aggregate([
  {
    $project: {
      firstNames: {
        $cond: {
          if: { $exists: [false] },
            then: '',
            else: '$firstName'
        }
      }
    },
    $project: {
      lastNames: {
        $cond: {
          if: { $exists: [false] },
          then: '',
          else: '$lastName'
        }
      }
    },
    $project: {
      fullName: {
        $concat: ['$firstNames', ' ', '$lastNames']
      }
    }
  }
]);
like image 652
guy Avatar asked Oct 17 '25 12:10

guy


1 Answers

You can use $addFields to replace initial values with defaults. The $ifNull operator allows you to return an empty string when there's no value.

db.collection.aggregate([
    {
        $addFields: {
            firstname: { $ifNull: [ "$firstname", "" ] },
            lastname: { $ifNull: [ "$lastname", "" ] },
        }
    },
    {
        $addFields: {
            fullName: { $trim: { input: { $concat: [ "$firstname", " ", "$lastname" ] } } }
        }
    }
])

Mongo Playground

like image 64
mickl Avatar answered Oct 19 '25 07:10

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!