![](/img/trans.png)
[英]Get the first 2 elements of an array in an aggregation query in MongoDB 3.0
[英]Join array elements using MongoDB aggregation framework
我有一個由MongoDB返回的數據數組。 我想知道如何使用mongodb聚合框架從下面的數組中連接名字和姓氏。
我看過幾條類似我的查詢的帖子,但是我不明白答案,因此我要發布一個新問題。
我已經寫了一個示例代碼,任何幫助糾正我的代碼的人都會非常感激
var playersData = [
{
firstName: 'David',
LastName: 'John',
country: 'India'
},
{
firstName: 'Chris',
LastName: 'Jericho',
country: 'USA'
},
{
firstName: 'John',
LastName: 'Cena',
country: 'USA'
}
];
碼
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) {
})
您可以嘗試以下匯總。
$match
保留玩家數組,其中至少一個國家/地區是USA,然后是$filter
來篩選國家/地區為USA的元素,以及$map
和$concat
來合並名字和姓氏以產生全名數組。
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"
]
}
}
}
}
}
])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.