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']
}
}
}
]);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With