mongodb group()统计(十)
  nQkVcpdWfLDr 2023年11月13日 24 0

分组统计: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()统计(十)_sql

统计价格数大于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;
}
})
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  nQkVcpdWfLDr   2023年11月13日   23   0   0 数据数据库SQL
nQkVcpdWfLDr