You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中实现两集合内连接并按商品标题统计数量

实现步骤

1. 获取订单与商品的关联列表

要筛选出orders中etc和desc均为空数组的文档,并与goods集合通过seqId和details.id匹配,得到指定格式的结果,可使用以下MongoDB聚合查询:

db.orders.aggregate([
  // 筛选etc和desc均为空数组的订单
  {
    $match: {
      etc: { $size: 0 },
      desc: { $size: 0 }
    }
  },
  // 关联goods集合,处理嵌套数组并匹配ID
  {
    $lookup: {
      from: "goods",
      let: { orderSeqId: "$seqId" },
      pipeline: [
        { $unwind: "$items" }, // 展开goods中的items数组
        { $unwind: "$items.details" }, // 展开items下的details数组
        { $match: { $expr: { $eq: ["$items.details.id", "$$orderSeqId"] } } }, // 匹配details.id与订单seqId
        { $project: { _id: 0, title: 1 } } // 只保留title字段
      ],
      as: "goodsInfo"
    }
  },
  { $unwind: "$goodsInfo" }, // 展开关联后的goodsInfo数组
  // 输出需要的字段
  {
    $project: {
      _id: 0,
      orderName: 1,
      title: "$goodsInfo.title"
    }
  }
])

执行后得到目标结果:

[
  { "orderName": "a", "title": "example1" },
  { "orderName": "b", "title": "example2" },
  { "orderName": "c", "title": "example1" }
]

2. 基于商品title统计数量

要统计每个title对应的订单数量,可在上述聚合逻辑基础上添加分组和格式转换步骤:

db.orders.aggregate([
  // 筛选符合条件的订单
  {
    $match: {
      etc: { $size: 0 },
      desc: { $size: 0 }
    }
  },
  // 关联goods集合,步骤与前序查询一致
  {
    $lookup: {
      from: "goods",
      let: { orderSeqId: "$seqId" },
      pipeline: [
        { $unwind: "$items" },
        { $unwind: "$items.details" },
        { $match: { $expr: { $eq: ["$items.details.id", "$$orderSeqId"] } } },
        { $project: { _id: 0, title: 1 } }
      ],
      as: "goodsInfo"
    }
  },
  { $unwind: "$goodsInfo" },
  // 按title分组统计订单数量
  {
    $group: {
      _id: "$goodsInfo.title",
      count: { $sum: 1 }
    }
  },
  // 将分组结果转换为指定的键值对格式
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: [[{ k: "$_id", v: "$count" }]]
      }
    }
  }
])

执行后得到统计结果:

[
  { "example1": 2 },
  { "example2": 1 }
]

内容的提问来源于stack exchange,提问作者newbieeyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:35:20