mongdb aggregate聚合操作

前端之家收集整理的这篇文章主要介绍了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}}},total:{$sum:1}}},{$match:{total:{$gte:3}}}
]


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


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


#查询每个栏目下的库存量,{$sort:{total:1}},{$limit:3}
]


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

猜你在找的设计模式相关文章