I have the following documents coming into my aggregation pipeline:
[
{
"email" : "[email protected]",
"name" : "Organization Name",
"users" : [
{
"lastName" : "Nye",
"firstName" : "Bill",
"email" : "[email protected]"
},
{
"lastName" : "Rogers",
"firstName" : "Mr.",
"email" : "[email protected]"
}
]
},
...
]
Using$project
I want to $concat
the firstName
and lastName
fields within each of the array subdocuments to get the following result:
{
"email" : "[email protected]",
"name" : "Organization Name",
"users" : [
{
"name" : "Bill Nye",
"email" : "[email protected]"
},
{
"name" : "Mr. Rogers",
"email" : "[email protected]"
}
]
}
I've tried the following aggregation:
db.organizations.aggregate([
{
$project: {
email : 1,
name : 1,
users : {
name : { $concat : [ "$users.firstName", " ", "$users.lastName" ] },
email : 1
}
}
}
]);
... but I get the following error:
$concat only supports strings, not Array
I've also tried the following aggregation:
db.organizations.aggregate([
{
$project: {
email : 1,
name : 1,
users : {
name : { $concat : [ "$firstName", " ", "$lastName" ] },
email : 1
}
}
}
]);
... but name
always returns null
.
I feel as if this should be a relatively simple thing to do, however, I'm completely stumped.
How do I get the results that I'm looking for?
You can simply do this by $project
ing your documents and use the $map
aggregation variable operator to apply the $concat
expression to each item in an array and returns an array with the applied results.
db.organizations.aggregate(
[
{ "$project": {
"email": 1,
"name": 1,
"users": {
"$map": {
"input": "$users",
"as": "u",
"in": {
"name": { "$concat" : [ "$$u.firstName", " ", "$$u.lastName" ] },
"email": "$$u.email"
}
}
}
}}
]
)
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