1、数据准备

查看前一篇group操作

 

2、aggregate函数参数讲解

mysql     mongdb
===================
WHERE --->$match GROUP BY --->$group HAVING --->$match SELECT --->$project ORDER BY --->$sort LIMIT --->$limit SUM() --->$sum COUNT() --->$sum

 

3、操作案例

#查询每个栏目下的商品数量
db.collection.aggregate();
[
{$group:{_id:"$cat_id",total:{$sum:1}}}
]

#查询goods下有多少条商品,select count(*) from goods
[
{$group:{_id:null,total:{$sum:1}}}
]


#查询每个栏目下 价格大于50元的商品个数
[
{$match:{shop_price:{$gt:50}}},
{$group:{_id:"$cat_id",total:{$sum:1}}}
]


#查询每个栏目下 价格大于50元的商品个数
#并筛选出"满足条件的商品个数" 大于等于3的栏目 
[
{$match:{shop_price:{$gt:50}}},
{$group:{_id:"$cat_id",total:{$sum:1}}},
{$match:{total:{$gte:3}}}
]


#查询每个栏目下的库存量
[
{$group:{_id:"$cat_id" , total:{$sum:"$goods_number"}}},
]


#查询每个栏目下的库存量,并按库存量排序
[
{$group:{_id:"$cat_id" , total:{$sum:"$goods_number"}}},
{$sort:{total:1}}
]


#查询每个栏目下的库存量,并按库存量排序
[
{$group:{_id:"$cat_id" , total:{$sum:"$goods_number"}}},
{$sort:{total:1}},
{$limit:3}
]


#查询每个栏目的商品平均价格,并按平均价格由高到低排序
[
{$group:{_id:"$cat_id" , avg:{$avg:"$shop_price"}}},
{$sort:{avg:-1}}
]

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-04-05
  • 2021-08-11
  • 2021-12-14
  • 2022-12-23
  • 2021-08-05
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2021-06-24
  • 2021-05-13
相关资源
相似解决方案