MongoDB聚合查询之分段分组查询统计

xiaohai 2020-06-04 16:47:44 4766人围观 标签: MongoDB 
简介MongoDB聚合查询之分段分组查询统计

在Mysql中我们经常会用到给某一个字段进行分段统计,然而在MongoDB数据库去处理这个统计应该如何做呢?

数据源说明:

  • data:表示集合
  • date:表示集合中的日期
  • satisfaction:表示集合中的满意度

需求:

  • 查询不同满意度分段的人数
db.getCollection("data").aggregate([{ $match: { date: 20200604 } }, { $project: { "count_field": { $switch: { branches: [ { case: { $eq: ["$satisfaction", 100] }, then: "100" }, { case: { $and: [{ $gte: ["$satisfaction", 95] }, { $lte: ["$satisfaction", 100] }] }, then: "[95,100)" }, { case: { $and: [{ $gte: ["$satisfaction", 90] }, { $lte: ["$satisfaction", 95] }] }, then: "[90,95)" }, { case: { $and: [{ $gte: ["$satisfaction", 85] }, { $lte: ["$satisfaction", 90] }] }, then: "[85,90)" }, { case: { $and: [{ $gte: ["$satisfaction", 80] }, { $lte: ["$satisfaction", 85] }] }, then: "[80,85)" }, { case: { $eq: ["$satisfaction", 0] }, then: "0" }, ], default: "(0,80)" } } } }, { $group: { _id: "$count_field", "总数": { $sum: 1 } } }, { $sort: { "_id":1 } }])

查询说明:

  • match:条件匹配
  • project:核心部分,这里使用了switch,进行条件判断,branches是固定的写法,不要修改
  • group:进行分组,根据project中的字段count_field作为分组字段
  • sort:排序,根据group中的_id

结果展示:

image.png