假设我有以下格式的传入数据:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [
{
"id": "test",
"cusId": "test",
"adr": "Adr 1",
"serviceCounty": "Center",
"area": "village"
},
{
"id": "test",
"cusId": "test",
"adr": "adr2",
"serviceCounty": "West",
"area": "city"
},
{
"id": "test",
"cusId": "test",
"adr": "test",
"serviceCounty": "West",
"area": "test"
}
]
}
任何想法,如何编写聚合查询:
所以最终结果是这样的:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [
{
"id": "test",
"cusId": "test",
"adr": "Adr 1",
"serviceCounty": "Center",
"area": "village"
},
{
"id": "test",
"cusId": "test",
"adr": "adr2",
"serviceCounty": "West",
"area": "city"
},
{
"id": "test",
"cusId": "test",
"adr": "test",
"serviceCounty": "West",
"area": "test"
}
],
"serviceAreas": [
"Adr 1, Center, village", "adr2, West, city"
]
}
感谢任何帮助!
这是我尝试过的,但没有成功:
'serviceAreas': {
'$reduce': {
'input': '$serviceImpactHistory.event.services',
'initialValue': [],
'in': {
'$setUnion': [
'$$value', {'$concat': ['$$this.serviceCounty', '$$this.adr', '$$this.area']}
]
}
}
},
答案 0 :(得分:1)
您不需要使用 $setUnion,只需使用 $concat 创建您的字符串
db.collection.aggregate([
{
$addFields: {
serviceAreas: {
"$reduce": {
"input": "$customerServices",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this.serviceCounty",
", ",
"$$this.adr",
", ",
"$$this.area",
", "
]
}
}
}
}
}
])