【发布时间】:2021-02-08 10:03:39
【问题描述】:
假设我有以下格式的传入数据:
{
"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、serviceCounty 和 area 字段。
- 将它们一起附加到一个字符串中,并添加到新创建的 serviceAreas 字段中。
- 它只会为不同的 serviceCounty 项目选择和执行操作
所以最终结果会是这样的:
{
"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']}
]
}
}
},
【问题讨论】:
-
您可以尝试使用$reduce 运算符。
-
是的,我明白了。但是,我有点无法理解整个事情。尝试将它与 $setUnion 和 $cascanate 一起使用,但它似乎不起作用。或者我做错了什么
-
尝试在网上搜索
$reduce的用法。另外,请包含您尝试过的代码,以便有人可以尝试帮助和解决问题。 -
更新了,我已经尝试过的问题
标签: python mongodb aggregation-framework pymongo