group聚合:
- key: 分组字段
- cond:过滤条件
- reduce:
- curr是当前行
- result是每组的结果集
- initial : 组变量初始值
- finalize: 统计一组后的回调函数
用group求每组count:
db.fruit.group({key:{"name": 1}, cond:{"fruitid": {$lt: 10}}, reduce: function(curr, result){ result.cnt += 1; }, initial: {cnt: 1}})
用group求每组sum:
db.fruit.group({key:{"name": 1}, cond:{"fruitid": {$lt: 10}}, reduce: function(curr, result){ result.cnt += curr.weight; }, initial: {cnt: 0}})
用group求每组最大最小值max/min:
db.fruit.group({key:{"name": 1}, cond:{"fruitid": {$lt: 10}}, reduce: function(curr, result){ if(curr.weight> result.cnt) result.cnt = curr.weight; }, initial: {cnt: 0}})
用group求每组平均值avg:
db.fruit.group({key:{"name": 1}, cond:{}, reduce: function(curr, result){ result.cnt += 1; result.sum += curr.weight }, initial: {cnt: 0, sum: 0}, finalize: function(result) { result.avg = result.sum / result.cnt; }})
注意:
Group不支持shard cluster, 无法分布式运算
分布式要使用aggregate(), mapReduce()