aggregate( )常用的几个操作:
1 $match
语法: db.COLLECTION_NAME.aggregate(options)
db.facilities.aggregate({$match:{name:/楼/}}).pretty() //效果与下面的find相同, pretty()用来格式化显示查到的数据 db.facilities.find({name:/楼/}).pretty()
2 $project
db.facilities.aggregate([{$match:{name:/楼/}},{$project:{_id:0,name:1,space:1}}]).pretty() //project中0表示不显示, 1则显示(_id默认显示)
3 $lookup
db.facilities.aggregate([
{$match:{name:/楼/}},
{$project:{_id:0,name:1,space:1}},
{$lookup:{from:‘spaces‘,localField:‘space‘,foreignField:‘_id‘,as:‘space‘}}]).pretty()
//from: 要连接的表 //localField: 当前表中的字段 //foreignField: 外表中连接的字段 //as: 给获得的值的字段名
4 $unwind
db.facilities.aggregate([
{$match:{name:/楼/}},
{$project:{_id:0,name:1,space:1}},
{$lookup:{from:‘spaces‘,localField:‘space‘,foreignField:‘_id‘,as:‘space‘}},
{$unwind:‘$space‘}]).pretty() //$unwind 拆分数组
5 $count
> db.facilities.aggregate([
{$match:{name:/楼/}},
{$project:{_id:0,name:1,space:1}},
{$lookup:{from:‘spaces‘,localField:‘space‘,foreignField:‘_id‘,as:‘space‘}},
{$unwind:‘$space‘},
{$count:‘厕所数量‘}]).pretty() //$count 统计记录条数, 并起别名
6 $group
db.facilities.aggregate([
{$match:{name:/楼/}},
{$lookup:{from:‘spaces‘,localField:‘space‘,foreignField:‘_id‘,as:‘space‘}},
{$unwind:‘$space‘},
{$lookup:{from:‘floors‘,localField:‘space.floor‘,foreignField:‘_id‘,as:‘floor‘}},
{$unwind:‘$floor‘},
{$project:{_id:0,name:1,floor:‘$floor.name‘}},
{$group:{_id:‘$floor‘,num:{$sum:1}}}]).pretty() //按floor分组, ($sum:1)每有一个加1, 值返回给num
类似于$sum, group 中还有$avg , $min, $max等
原文:https://www.cnblogs.com/yh2020/p/13378599.html