![](/img/trans.png)
[英]how to get Python Mongo Aggregate explain using db.command?
[英]How to aggregate distinct items in mongo db to separate array?
我有一个 API 端点,它检查 mongo db 并以以下结构返回,例如:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "West",
"name": "test"
},
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "West",
"name": "test"
},
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "East",
"name": "test"
}
]
}
我想要做的是将聚合添加到管道中,这将创建额外的 field-serviceCounties并包含来自 customerServices 数组的不同serviceCounty 值。 如下所示:
{
"Name": "Test"
"Location": "Whatever",
"customerServices": [
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "West",
"name": "test"
},
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "West",
"name": "test"
},
{
"id": "test",
"cusId": "test",
"serviceAdr": "test",
"serviceCounty": "East",
"name": "test"
}
],
"serviceCounties": [
{
"countyName":"East"
},
{
"countyName":"West"
}
]
}
我尝试了以下方法,但没有奏效。 我缺少一些东西或做错了:
'serviceCounties': {
'$reduce': {
'input': '$services.event.services',
'initialValue': [],
'in': [{
"countyName": { '$concatArrays': ["$$value.serviceCounty", "$$this"] }
}]
}
}
任何想法如何做到这一点?
你可以试试这个。
db.collection.aggregate([
{
$addFields: {
"serviceCounties": [
{
$map: {
input: "$customerServices",
in: {
"countyName": "$$this.serviceCounty"
}
}
}
]
}
}
])
$addfields添加serviceCounties数组
$map以获取customerServices值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.