I have an array of data returned by MongoDB. I would like to know how to join first name and last name from the below array using mongodb aggregation framework.
i have seen couple of posts similer to my query,however i did not understand the answer and hence i am posting a new question.
I have written a sample code.any helping corrcting my code would be really appreciated
var playersData = [
{
firstName: 'David',
LastName: 'John',
country: 'India'
},
{
firstName: 'Chris',
LastName: 'Jericho',
country: 'USA'
},
{
firstName: 'John',
LastName: 'Cena',
country: 'USA'
}
];
code
playerModel.aggregate([
{
"$match": {
[{ "country": 'USA' }]
}
},
{
"$project": {
"_id": 0, "playersData.firstName": 1, "playersData.lastName": 1,
fullName: {
$reduce: {
input: '$playersData',
initialValue: '',
in: {
$concat: ["$$value", "$$this"]
}
}
}
}
}
], function (err, result) {
})
You can try below aggregation.
$match
to keep player array where at least one of the country is USA followed by $filter
to filter elements with country as USA and $map
with $concat
to join the first name and last name to produce the full name array.
playerModel.aggregate([
{
"$match": {
"playersData.country": "USA"
}
},
{
"$project": {
"_id": 0,
"playersData.firstName": 1,
"playersData.lastName": 1,
"fullname": {
"$map": {
"input": {
"$filter": {
"input": "$playersData",
"as": "playerf",
"cond": {
"$eq": [
"$$playerf.country", "USA"
]
}
}
},
"as": "playerm",
"in": {
"$concat": [
"$$playerm.firstName",
",",
"$$playerm.lastName"
]
}
}
}
}
}
])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.