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']
}
}
}
]);