聚合案例示范

以下示例展示了几个常见的聚合场景,帮助理解聚合管道的实际应用。

案例一:统计用户按性别分组的数量

统计用户集合中各性别的用户数量:

db.users.aggregate([
  {
    $group: {
      _id: "$gender",
      count: { $sum: 1 }
    }
  }
])

`

输出类似:

{ "_id": "male", "count": 100 }
{ "_id": "female", "count": 120 }

案例二:计算每个类别的总销售额

统计商品集合中每个类别的销售总额:

db.products.aggregate([
  {
    $group: {
      _id: "$category",
      totalSales: { $sum: "$price" }
    }
  }
])

案例三:筛选并排序用户,返回部分字段

查询年龄大于 25 岁的用户,按年龄升序排序,只返回用户名和年龄:

db.users.aggregate([
  { $match: { age: { $gt: 25 } } },
  { $sort: { age: 1 } },
  { $project: { username: 1, age: 1, _id: 0 } }
])

案例四:展开数组字段并统计标签出现次数

假设文章有 tags 数组,统计每个标签的出现频率:

db.articles.aggregate([
  { $unwind: "$tags" },
  {
    $group: {
      _id: "$tags",
      count: { $sum: 1 }
    }
  },
  { $sort: { count: -1 } }
])

通过这些聚合案例,可以更好地掌握 MongoDB 聚合管道的灵活性和强大功能。