进阶三板斧:$lookup 连表、$facet 多维统计、$bucket 分桶。本文讲它们的用法与注意,结尾附订单报表小案例。
一、$lookup:连表(类 JOIN)
// 订单连用户表,带出用户名
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $lookup: {
from: "users", // 关联集合
localField: "userId", // 本集合字段
foreignField: "_id", // 外集合字段
as: "userInfo" // 输出数组字段
}},
{ $unwind: "$userInfo" }, // 数组转单对象
{ $project: {
no: 1, amount: 1,
userName: "$userInfo.name",
_id: 0
}}
])
| 要点 | 说明 |
|---|---|
| as 输出是数组 | 配 $unwind 打平(查不到时数组为空) |
| 相当于 LEFT JOIN | 无匹配时 as 为 [] |
| 性能 | foreignField 应有索引;大数据量慎用 |
| 嵌套 lookup | 管道式 $lookup 可带条件(4.0+) |
二、$unwind 进阶
{ $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }
// 空数组/缺失字段的文档也保留(否则会被丢弃)
三、$facet:一次查询出多个统计
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $facet: {
byCategory: [
{ $group: { _id: "$categoryId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
],
byStatus: [
{ $group: { _id: "$status", count: { $sum: 1 } } }
],
summary: [
{ $group: { _id: null, total: { $sum: "$amount" }, avg: { $avg: "$amount" } } }
]
}}
])
一次扫描出多维报表(仪表盘常用)—— 比跑多条聚合省 I/O。
四、$addFields 与 $bucket
// 派生字段
{ $addFields: { profit: { $subtract: ["$amount", "$cost"] } } }
// 金额分桶统计
{ $bucket: {
groupBy: "$amount",
boundaries: [0, 100, 500, 1000, Infinity],
default: "other",
output: { count: { $sum: 1 }, total: { $sum: "$amount" } }
}}
五、注意
- $lookup 后没有索引保护,关联集合大时慢(能冗余就冗余,见模型设计篇);
- $facet 内每个子管道共享 $facet 前的数据,输出限制 16MB(可 $limit 截断);
- $unwind 默认丢弃空数组文档 —— 记得 preserveNullAndEmptyArrays;
- 复杂聚合先 $match 缩数据量再算。
六、小案例:订单报表仪表盘
// 一个管道输出:TOP5 用户、金额分布、月度趋势
db.orders.aggregate([
{ $match: { status: "paid", created: { $gte: ISODate("2026-01-01") } } },
{ $facet: {
topUsers: [
{ $group: { _id: "$userId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 5 },
{ $lookup: { from: "users", localField: "_id", foreignField: "_id", as: "u" } },
{ $unwind: "$u" },
{ $project: { name: "$u.name", total: 1, _id: 0 } }
],
amountBuckets: [
{ $bucket: {
groupBy: "$amount",
boundaries: [0, 100, 500, 1000, Infinity],
output: { count: { $sum: 1 } }
}}
],
monthly: [
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$created" } },
total: { $sum: "$amount" }
}},
{ $sort: { _id: 1 } }
]
}}
], { allowDiskUse: true })
$facet 三块报表 + topUsers 内嵌 $lookup 连表 —— 仪表盘一个接口搞定。
七、总结
$lookup = LEFT JOIN(foreignField 要索引);$unwind 空数组记得保留;$facet 多维统计一扫多出;$bucket 分桶、$addFields 派生字段。