【发布时间】:2020-01-31 22:04:23
【问题描述】:
我正在尝试根据以下数据编写嵌套组查询:
[
{
"mmyy": "JAN-2019",
"location": "Boston",
"category": "Shoes",
"qty": 5
},
{
"mmyy": "JAN-2019",
"location": "New York",
"category": "Shoes",
"qty": 10
},
{
"mmyy": "JAN-2019",
"location": "Boston",
"category": "Hats",
"qty": 2
},
{
"mmyy": "JAN-2019",
"location": "New York",
"category": "Hats",
"qty": 3
},
{
"mmyy": "FEB-2019",
"location": "Boston",
"category": "Shoes",
"qty": 5
},
{
"mmyy": "FEB-2019",
"location": "New York",
"category": "Hats",
"qty": 10
},
]
想要的结果:
[
{
month: "JAN-2019",
month_total: 20,
locations:[
{
name: "Boston",
location_total: 7,
categories: [
{name: "Shoes", total: 5},
{name: "Hats", total: 2},
]
}
...
]
},
...
]
我能够达到第二级聚合(对于月份和位置),但是很难将所有聚合归结为嵌套结果中的类别。这就是我所做的,使用多个$group 和$push:
db.sales.aggregate([
{$group: {
_id:{ month: "$mmyy", location: "$location"},
total: { $sum: "$qty"}
}},
{ $group:{
_id: "$_id.month",
monthly_total: { $sum: "$total" },
locations: {
$push:{
name: "$_id.location",
total: "$total"
}
}
}}
])
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework grouping