MongoDB 聚合管道实战:复杂数据分析的利器

MongoDB Aggregation Pipeline in Practice A Powerhouse for Complex Data Analysis

| iDev Team | 2026-07-31T05:47:00

MongoDB 的聚合管道是处理复杂数据查询的强大工具。本文通过电商数据分析的实际案例,详解 $match、$group、$lookup 等核心操作。

MongoDB's aggregation pipeline is a powerful tool for complex data queries. This article explains core operations like $match, $group, and $lookup through real e-commerce analytics examples.

什么是聚合管道 聚合管道(Aggregation Pipeline)是 MongoDB 处理数据转换和分析的框架。它由多个阶段(Stage)组成,数据像流水线一样依次通过每个阶段,每个阶段对数据进行一次变换。 核心阶段操作 $match:过滤文档(类似 SQL 的 WHERE) $group:分组聚合(类似 SQL 的 GROUP BY) $sort:排序 $project:字段映射和计算(类似 SQL 的 SELECT) $lookup:关联查询(类似 SQL 的 JOIN) $unwind:展开数组 $facet:并行执行多个管道 实战案例:电商销售分析 案例 1:每日销售额统计 db.orders.aggregate([ { $match: { status: "completed", createdAt: { $gte: ISODate("2026-01-01") } } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, totalSales: { $sum: "$amount" }, orderCount: { $sum: 1 } } }, { $sort: { _id: -1 } } ]) 案例 2:热销商品 Top 10 db.orders.aggregate([ { $unwind: "$items" }, { $group: { _id: "$items.productId", totalQty: { $sum: "$items.quantity" }, revenue: { $sum: { $multiply: ["$items.price", "$items.quantity"] } } } }, { $sort: { revenue: -1 } }, { $limit: 10 }, { $lookup: { from: "products", localField: "_id", foreignField: "_id", as: "product" } }, { $unwind: "$product" }, { $project: { name: "$product.name", totalQty: 1, revenue: 1 } } ]) 性能优化技巧 $match 尽量放在管道最前面,利用索引过滤 使用 allowDiskUse: true 处理大数据集 用 $project 在早期阶段剔除不需要的字段 为 $lookup 的关联字段建立索引 与 SQL 的对比 如果你来自 SQL 背景,聚合管道的学习曲线会比较陡。但一旦掌握,它在处理嵌套文档、数组操作和多步骤数据转换方面比 SQL 更灵活。对于结构化数据和简单查询,SQL 仍然更直观。


What is the Aggregation Pipeline The Aggregation Pipeline is MongoDB's framework for data transformation and analysis. It consists of multiple stages where data flows through each stage sequentially, with each stage performing one transformation. Core Stage Operations $match: Filter documents (like SQL WHERE) $group: Group aggregation (like SQL GROUP BY) $sort: Sorting $project: Field mapping and computation (like SQL SELECT) $lookup: Join queries (like SQL JOIN) $unwind: Flatten arrays $facet: Run multiple pipelines in parallel Performance Tips Put $match at the beginning of the pipeline to leverage indexes Use allowDiskUse: true for large datasets Use $project early to drop unnecessary fields Index fields used in $lookup joins

← Back to News