MongoDB 学习笔记之 group聚合

mac2022-06-30  63

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()

 

转载于:https://www.cnblogs.com/AK47Sonic/p/7401117.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)