微信登录

命令 - 查 - 聚合管道

常见操作符

  1. $match‌:过滤数据‌
  2. $group:按指定字段分组‌
  3. $project‌:选择或重命名字段‌
  4. $sort:排序输出结果
  5. $limit:限制输出数量‌
  6. $sum:计算总和
  7. $lookup:关联其他集合数据

1. 基础分组统计

统计 orders 集合中每个产品的总销量:

javascript

  1. db.orders.aggregate([
  2. { $unwind: "$items" }, // 展开订单中的商品数组
  3. {
  4. $group: {
  5. _id: "$items.productId",
  6. totalSold: { $sum: "$items.quantity" } // 计算总销量
  7. }
  8. }
  9. ])

2. 多阶段管道:过滤 + 分组 + 排序

查询 2023年单价超过 \$100 的商品,按总销售额降序排列:

javascript

  1. db.orders.aggregate([
  2. { $match: { orderDate: { $gte: ISODate("2023-01-01") } } }, // 过滤日期
  3. { $unwind: "$items" },
  4. { $match: { "items.price": { $gt: 100 } } }, // 过滤价格
  5. {
  6. $group: {
  7. _id: "$items.productId",
  8. totalSales: { $sum: { $multiply: ["$items.price", "$items.quantity"] } } // 计算销售额
  9. }
  10. },
  11. { $sort: { totalSales: -1 } } // 降序排序
  12. ])

3. 联表查询 (\$lookup)

products 集合关联到订单详情:

javascript

  1. db.orders.aggregate([
  2. { $unwind: "$items" },
  3. {
  4. $lookup: {
  5. from: "products", // 目标集合
  6. localField: "items.productId",
  7. foreignField: "_id",
  8. as: "productDetails" // 关联结果存储字段
  9. }
  10. },
  11. { $unwind: "$productDetails" } // 展开关联数组
  12. ])

4. 条件计算 (\$cond)

为订单添加 高价值订单 标签(总价 > \$500):

javascript

  1. db.orders.aggregate([
  2. {
  3. $addFields: {
  4. totalAmount: { $sum: "$items.price" } // 临时计算字段
  5. }
  6. },
  7. {
  8. $project: {
  9. orderId: 1,
  10. isHighValue: {
  11. $cond: {
  12. if: { $gt: ["$totalAmount", 500] },
  13. then: "Yes",
  14. else: "No"
  15. }
  16. }
  17. }
  18. }
  19. ])

5. 时间维度分析

月份 统计销售额:

javascript

  1. db.orders.aggregate([
  2. {
  3. $group: {
  4. _id: {
  5. year: { $year: "$orderDate" },
  6. month: { $month: "$orderDate" }
  7. },
  8. monthlySales: { $sum: "$total" }
  9. }
  10. },
  11. { $sort: { "_id.year": 1, "_id.month": 1 } } // 按年月排序
  12. ])

6. 分页处理 (\$skip + \$limit)

实现分页查询(第2页,每页10条):

javascript

  1. db.orders.aggregate([
  2. { $sort: { orderDate: -1 } }, // 先排序
  3. { $skip: 10 }, // 跳过第一页
  4. { $limit: 10 } // 取第二页
  5. ])

7. 数组操作 (\$filter)

筛选订单中 数量大于3 的商品:

javascript

  1. db.orders.aggregate([
  2. {
  3. $project: {
  4. orderId: 1,
  5. heavyItems: {
  6. $filter: {
  7. input: "$items",
  8. as: "item",
  9. cond: { $gt: ["$$item.quantity", 3] }
  10. }
  11. }
  12. }
  13. }
  14. ])