【发布时间】:2020-05-13 05:15:19
【问题描述】:
我有一个 mongoDB 集合,我想做一个聚合查询。
我按alert_type 字段分组,但我还希望将那些alert_type 的列表作为输出中的单独字段。
集合看起来像这样:
db.test.insertMany([
{
"output_data": {
"alert_type": "UAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
},
{
"output_data": {
"alert_type": "CAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
},
{
"output_data": {
"alert_type": "UAlert",
"overallImpact": {
"margin": 0.1,
"workingCapital": 3.33
}
}
}
])
我尝试过的查询:
db.test.aggregate([
{$group: {
"_id": "$output_data.alert_type",
"alert_type": {
"$first": "$output_data.alert_type"
},
"margin": {
"$sum": "$output_data.overallImpact.margin"
},
"workingCapital": {
"$sum": "$output_data.overallImpact.workingCapital"
},
"alert_types": {
"$addToSet": "$output_data.alert_type"
}
}
},
{$project: {'_id': 0
}
}
])
电流输出:
{
"alert_type": "UAlert",
"margin": 0.2,
"workingCapital": 6.66,
"alert_types": [
"UAlert"
]
}
{
"alert_type": "CAlert",
"margin": 0.1,
"workingCapital": 3.33,
"alert_types": [
"CAlert"
]
}
所需输出:
{
"data": [
{
"alert_type": "UAlert",
"margin": 0.2,
"workingCapital": 6.66,
},
{
"alert_type": "CAlert",
"margin": 0.1,
"workingCapital": 3.33,
}
],
"alert_types": [
"UAlert",
"CAlert"
]
}
谁能帮我解决这个问题?
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework