Reputation: 111
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']
}
}
}
]);
Upvotes: 4
Views: 3737
Reputation: 61774
Starting in Mongo 5.3
, it's a nice use case for the new $fill
aggregation operator:
// { firstName: "John", lastName: "Smith" }
// { firstName: "John" }
db.collection.aggregate([
{ $fill: { output: { firstName: { value: "John" }, lastName: { value: "Doe" } } } },
{ $set: { fullName: { $concat: ["$firstName", " ", "$lastName"] } } }
])
// { firstName: "John", lastName: "Smith", fullName: "John Smith" }
// { firstName: "John", lastName: "Doe", fullName: "John Doe" }
Missing values or values set to null
are fill
ed with the given constant (for instance Doe
for last names).
Upvotes: 0
Reputation: 49995
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" ] } } }
}
}
])
Upvotes: 7