Aggregate.group(object: Object): Aggregate
聚合阶段。将输入记录按给定表达式分组,输出时每个记录代表一个分组,每个记录的 是区分不同组的 key。输出记录中也可以包括累计值,将输出字段设为累计值即会从该分组中计算累计值。
Aggregate
group
的形式如下:
累计器必须是以下操作符之一:
- addToSet
- avg
- first
- last
- max
- min
- push
- stdDevPop
- stdDevSamp
- sum
内存限制
该阶段有 100M 内存使用限制。
{
_id: "1",
alias: "john",
region: "asia",
scores: [40, 20, 80],
coins: 100
}
{
_id: "2",
alias: "arthur",
region: "europe",
scores: [60, 90],
coins: 20
}
_id: "3",
alias: "george",
region: "europe",
scores: [50, 70, 90],
coins: 50
}
{
_id: "4",
alias: "john",
scores: [30, 60, 100, 90],
coins: 40
}
{
_id: "5",
alias: "george",
region: "europe",
scores: [20],
coins: 60
}
{
_id: "6",
alias: "john",
region: "asia",
scores: [40, 80, 70],
coins: 120
}
返回结果如下:
{
"_id": "john",
"num": 3
}
{
"num": 1
}
{
"_id": "george",
"num": 2
可以给 _id
传入记录的方式按多个值分组。还是沿用上面的示例数据,按各个区域(region)获得相同最高分(score)的来分组,并求出各组虚拟币(coins)的总量:
{
"_id": {
"region": "asia",
"maxScore": 80
},
"totalCoins": 220
}
{
"_id": {
"region": "asia",
"maxScore": 100
},
"totalCoins": 100
}
{
"_id": {
"region": "europe",
"maxScore": 90
},
"totalCoins": 70
}
{
"_id": {
"region": "europe",
"maxScore": 20
},