聚合管道 = 把数据像流水线一样逐阶段加工($match → $group → $sort…)。本文讲常用前几个阶段,结尾附销售统计小案例。
一、管道概念
db.collection.aggregate([ 阶段1, 阶段2, … ])
每个阶段:{ $操作符: 参数 }
数据逐阶段流转 → 最终输出结果
二、$match:过滤(尽量放第一段)
db.orders.aggregate([
{ $match: { status: "paid", created: { $gte: ISODate("2026-01-01") } } },
// … 后续阶段只处理过滤后的数据
])
$match 放最前可利用索引、减少后续处理量 —— 与 SQL 的 WHERE 同理。
三、$group:分组统计
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: {
_id: "$categoryId", // 分组键($字段)
totalAmount: { $sum: "$amount" }, // 求和
avgAmount: { $avg: "$amount" }, // 平均
maxAmount: { $max: "$amount" }, // 最大
count: { $sum: 1 } // 计数技巧
}}
])
| 累加器 | 作用 |
|---|---|
| $sum / $avg | 求和 / 平均 |
| $max / $min | 最大 / 最小 |
| $first / $last | 组内首 / 末 |
| $push / $addToSet | 收集为数组 / 去重收集 |
| $count | 计数(4.4+ 阶段版更简) |
四、$sort / $project / $limit / $skip
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$userId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $project: { userId: "$_id", total: 1, _id: 0 } }, // 重命名/裁剪
{ $skip: 0 },
{ $limit: 10 }
])
$project 里可计算:{ totalWithTax: { $multiply: ["$amount", 1.13] } }。
五、$unwind:拆数组
// 订单里 tags 数组拆成多行,按标签统计
db.orders.aggregate([
{ $unwind: "$tags" },
{ $group: { _id: "$tags", count: { $sum: 1 } } },
{ $sort: { count: -1 } }
])
六、注意
- 管道阶段顺序重要:$match/$sort 尽量靠前吃索引;
- $group 的 _id 是必填(不分组用 _id: null);
- 大集合聚合用
allowDiskUse: true防 100MB 内存上限报错; - 聚合结果是游标(可 toArray/forEach)。
七、小案例:月度销售统计
// 统计 2026 年各分类销售额 TOP10
db.orders.aggregate([
{ $match: {
status: "paid",
created: { $gte: ISODate("2026-01-01"), $lt: ISODate("2027-01-01") }
}},
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$created" } }, // 按月
totalAmount: { $sum: "$amount" },
orderCount: { $sum: 1 },
avgAmount: { $avg: "$amount" }
}},
{ $sort: { totalAmount: -1 } },
{ $project: {
month: "$_id",
totalAmount: { $round: ["$totalAmount", 2] },
orderCount: 1,
avgAmount: { $round: ["$avgAmount", 2] },
_id: 0
}},
{ $limit: 10 }
], { allowDiskUse: true })
// 输出形如:
// { month: "2026-11", totalAmount: 125000.5, orderCount: 320, avgAmount: 390.63 }
$match 过滤 → $group 按月聚合 → $sort 排序 → $project 格式化 —— 一条管道出报表,等价 SQL 的 GROUP BY 但更灵活。
八、总结
管道阶段 $match/$group/$sort/$project 是核心;$group 累加器 $sum/$avg/$push;$unwind 拆数组;match/sort 靠前、大聚合加 allowDiskUse。