首页 > 技术文章 > mongodb 聚合操作

timelesszhuang 2017-03-07 23:03 原文

1、首先举例分析下 mongodb 的聚合操作:  

 

  • 该操作表示根据whoisserver_id 字段分组 来统计每个分组下的 count数量:
db.anhui.aggregate({$group:{_id:'$whoisserver_id',total:{$sum:1}}})

查询出来的结果如下:

  • 如果查询总的数量:
db.anhui.aggregate({$group:{_id:null,total:{$sum:1}}})

 

  • 以下查询先根据条件过滤然后统计  
db.anhui.aggregate({$match:{mx:{$exists:1}}},{$group:{_id:'$whoisserver_id',total:{$sum:1}}})
  • 首先过滤数据相当于 sql 语句中where 操作,然后分组 count  ,然后 匹配数量大于30的 信息
db.anhui.aggregate({$match:{mx:{$exists:1}}},{$group:{_id:'$whoisserver_id',total:{$sum:1}}},{$match:{total:{$gte:30}}})

 

以下为查询到的数据

查询 

db.anhui.aggregate({$match:{mx:{$exists:1}}},{$group:{_id:'$mx.brand_id',total:{$sum:1}}})

 

推荐阅读