MongoDB 聚合管道实战:数据分析完全指南
MongoDB 聚合管道实战:数据分析完全指南

MongoDB 聚合管道实战:数据分析完全指南

MongoDB 聚合管道实战:数据分析完全指南

MongoDB 的聚合管道(Aggregation Pipeline)是强大的数据分析工具。本文深入讲解聚合管道的核心操作和实战技巧。

🚀 聚合管道基础

聚合管道由多个阶段(stage)组成,每个阶段对文档进行转换:

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$userId", total: { $sum: "$amount" } } },
  { $sort: { total: -1 } },
  { $limit: 10 }
])

📊 常用聚合阶段

1. $match:筛选文档

{ $match: {
  createdAt: { $gte: ISODate("2025-01-01") },
  status: { $in: ["completed", "shipped"] }
}}

2. $group:分组聚合

{ $group: {
  _id: "$category",
  count: { $sum: 1 },
  avgPrice: { $avg: "$price" },
  maxPrice: { $max: "$price" },
  totalSales: { $sum: "$quantity" }
}}

3. $project:字段投影

{ $project: {
  name: 1,
  total: { $multiply: ["$price", "$quantity"] },
  _id: 0
}}

4. $unwind:展开数组

// 原始文档:{ tags: ["mongodb", "database", "nosql"] }
// 展开后:3 个文档,每个包含一个 tag
{ $unwind: "$tags" }

5. $lookup:关联查询

{ $lookup: {
  from: "users",
  localField: "userId",
  foreignField: "_id",
  as: "userInfo"
}}

🔥 实战案例

案例1:电商订单分析

db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2025-01-01") } } },
  { $unwind: "$items" },
  { $group: {
    _id: "$items.productId",
    totalSold: { $sum: "$items.quantity" },
    revenue: { $sum: { $multiply: ["$items.price", "$items.quantity"] } }
  }},
  { $sort: { revenue: -1 } },
  { $limit: 10 }
])

案例2:用户行为漏斗分析

db.events.aggregate([
  { $match: { eventType: { $in: ["page_view", "add_to_cart", "purchase"] } } },
  { $group: {
    _id: "$eventType",
    count: { $sum: 1 }
  }},
  { $sort: { _id: 1 } }
])

⚡ 性能优化

  1. 尽早使用 $match:减少后续阶段处理的文档数
  2. 使用索引:$match、$sort、$group 阶段可以利用索引
  3. 限制返回文档数:使用 $limit 减少数据传输
  4. 避免 $unwind 大数组:可能导致文档爆炸

🛠️ 实用技巧

  • 使用 $addFields 添加计算字段
  • 使用 $facet 在同一管道中执行多个聚合
  • 使用 $bucket 进行分桶分析
  • 使用 $graphLookup 进行图遍历

总结:MongoDB 聚合管道功能强大,能满足大部分数据分析需求。掌握常用聚合阶段和性能优化技巧,能大幅提升数据处理效率。


本文整理自 MongoDB 官方文档及聚合管道实战教程

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注