Aggregate.group(object: Object): Aggregate

聚合阶段。将输入记录按给定表达式分组,输出时每个记录代表一个分组,每个记录的 是区分不同组的 key。输出记录中也可以包括累计值,将输出字段设为累计值即会从该分组中计算累计值。

Aggregate

group 的形式如下:

累计器必须是以下操作符之一:

  • addToSet
  • avg
  • first
  • last
  • max
  • min
  • push
  • stdDevPop
  • stdDevSamp
  • sum

内存限制

该阶段有 100M 内存使用限制。

  1. {
  2. _id: "1",
  3. alias: "john",
  4. region: "asia",
  5. scores: [40, 20, 80],
  6. coins: 100
  7. }
  8. {
  9. _id: "2",
  10. alias: "arthur",
  11. region: "europe",
  12. scores: [60, 90],
  13. coins: 20
  14. }
  15. _id: "3",
  16. alias: "george",
  17. region: "europe",
  18. scores: [50, 70, 90],
  19. coins: 50
  20. }
  21. {
  22. _id: "4",
  23. alias: "john",
  24. scores: [30, 60, 100, 90],
  25. coins: 40
  26. }
  27. {
  28. _id: "5",
  29. alias: "george",
  30. region: "europe",
  31. scores: [20],
  32. coins: 60
  33. }
  34. {
  35. _id: "6",
  36. alias: "john",
  37. region: "asia",
  38. scores: [40, 80, 70],
  39. coins: 120
  40. }

返回结果如下:

  1. {
  2. "_id": "john",
  3. "num": 3
  4. }
  5. {
  6. "num": 1
  7. }
  8. {
  9. "_id": "george",
  10. "num": 2

可以给 _id 传入记录的方式按多个值分组。还是沿用上面的示例数据,按各个区域(region)获得相同最高分(score)的来分组,并求出各组虚拟币(coins)的总量:

  1. {
  2. "_id": {
  3. "region": "asia",
  4. "maxScore": 80
  5. },
  6. "totalCoins": 220
  7. }
  8. {
  9. "_id": {
  10. "region": "asia",
  11. "maxScore": 100
  12. },
  13. "totalCoins": 100
  14. }
  15. {
  16. "_id": {
  17. "region": "europe",
  18. "maxScore": 90
  19. },
  20. "totalCoins": 70
  21. }
  22. {
  23. "_id": {
  24. "region": "europe",
  25. "maxScore": 20
  26. },