【发布时间】:2018-08-22 19:04:33
【问题描述】:
我想为以下示例数组聚合数据。
[
{
"_id": "5b7c0540342100091a375793",
"pages": [
{
"name": "ABCD",
"sections": [
{
"name": "sectionThird",
"id": 2,
"value": [
10,
50,
20
]
}
]
}
]
},
{
"_id": "5b3cd546342100514b4683a2",
"pages": [
{
"name": "ABCD",
"sections": [
{
"name": "sectionFourth",
"id": 2,
"value": [
19,
5,
8
]
},
{
"name": "sectionThird",
"id": 2,
"value": [
60
]
}
]
},
{
"name": "EFGH",
"sections": [
{
"name": "sectionFourth",
"id": 2,
"value": [
5
]
},
{
"name": "sectionThsads",
"id": 2,
"value": [
8
]
}
]
}
]
}
]
我想要以下输出:
[
{
"page": "ABCD",
"sections": [
{
"name": "sectionThird",
"totalValue": 140
},
{
"name": "sectionFourth",
"totalValue": 32
}
]
},
{
"page": "EFGH",
"sections": [
{
"name": "sectionFourth",
"totalValue": 5
},
{
"name": "sectionThsads",
"totalValue": 8
}
]
}
]
在上面的示例数组中,您可以看到有多个以“page”作为键之一的文档,它们也是一个对象数组。每个页面对象都有一个键“名称”,这对于“页面”数组中的每个对象都是唯一的。 “page”对象有“sections”键,它们也有“name”键,每个对象都是唯一的。
因此,输出数组按 page.name 分组,然后按sections.name 分组,来自所有页面对象,并且具有相同节名的页面对象内的所有节中的所有值数组的总和。
【问题讨论】:
标签: mongodb aggregation-framework