聚合操作概述
MongoDB 的聚合框架通过构建数据处理管道来对文档进行复杂转换和分析。
聚合管道阶段
- $match:筛选符合条件的文档
- $group:根据指定字段对文档进行分组
- $project:选择或重命名输出字段
- $sort:对结果进行排序
- $limit:限制输出文档数量
- $skip:跳过文档
常用操作详解
$match 匹配过滤
db.users.aggregate([
{
$match: {
age: { $gt: 18 },
status: "active"
}
}
])
$group 分组操作
db.orders.aggregate([
{ $match: { status: "completed" } },
{
$group: {
_id: "$customer_id",
total: { $sum: "$amount" },
avg: { $avg: "$amount" }
}
}
])
$project 投影操作
db.orders.aggregate([
{
$project: {
customer: 1,
total: { $multiply: ["$price", "$quantity"] },
_id: 0
}
}
])
$sort 排序操作
db.employees.aggregate([
{
$sort: {
department: 1,
salary: -1
}
}
])
性能优化建议
- 尽量在管道前端使用
$match减少处理文档数量 - 合理使用索引加速聚合查询
- 避免在
$group阶段处理大量数据 - 考虑使用 allowDiskOption 选项处理大数据集