mongdb aggregate聚合操作

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}}
]

 

posted @ 2019-01-06 00:03  小白啊小白,Fighting  阅读(310)  评论(0编辑  收藏  举报