mongodb group()统计(十)

时间:2022-09-10 00:41:57

分组统计:group()           注:不支持分片集群,无法分布式运算

简单聚合:aggregate()       注:支持集群分片(2.2版本增加)

强大统计:mapReduce()       注:支持集群分片(2.4版本增加)

1.计算每个栏目下的商品count()操作

sql写法:select cat_id,count(*) total  from goods group by cat_id

mongodb写法:

db.goods.group({
key:{cat_id:1},
cond:{},
reduce:function(curr,result){
result.total++;
},
initial:{total:0}
})

mongodb group()统计(十)

统计价格数大于50块的商品

sql写法:select cat_id,count(*) total from goods where shop_price > 50 group by cat_id

mongodb写法: 

db.goods.group({
key:{cat_id:1},
cond:{shop_price:{$gt:50}},
reduce:function(curr,result){
result.total++;
},
initial:{total:0}
})

2.计算每个栏目下的商品库存量sum()操作

sql语法:select cat_id,sum(goods_number) total from goods group by cat_id

mongodb写法:

db.goods.group({
key:{cat_id:1},
cond:{},
reduce:function(curr,result){
result.goods_number += curr.goods_number;
},
initial:{goods_number:0}
})

3.计算每个栏目下最贵的商品价格

sql语法:select cat_id,max(shop_price) total from goods group by cat_id

mongodb写法:

db.goods.group({
key:{cat_id:1},
cond:{},
reduce:function(curr,result){
if(result.max < curr.shop_price){
result.max = curr.shop_price
}
},
initial:{max:0}
})

4.查询每个栏目下商品的平均价格

sql写法:select cat_id,avg(shop_price) total from goods group by cat_id

mongodb写法:

db.goods.group({
key:{cat_id:1},
cond:{},
reduce:function(curr,result){
result.cnt++;
result.sum += curr.shop_price;
},
initial:{sum:0,cnt:0},
finalize:function(result){
result.avg = result.sum/result.cnt;
}
})