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

MongoDB聚合查询:如何关联多集合并返回关联完整数据?

MongoDB聚合查询:关联多集合获取完整数据

以下是满足需求的聚合查询语句,通过嵌套$lookup实现多集合关联,将ID替换为对应集合的完整数据:

await category.aggregate([
  {
    $match: {
      _id: 1
    }
  },
  {
    $lookup: {
      from: "store",
      let: { cid: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [ { $toInt: "$category_id" }, "$$cid" ]
            }
          }
        },
        {
          $lookup: {
            from: "sticker",
            localField: "sticker_id",
            foreignField: "_id",
            as: "stickerData"
          }
        },
        {
          $addFields: {
            stickerData: { $arrayElemAt: [ "$stickerData", 0 ] }
          }
        },
        {
          $lookup: {
            from: "prefix",
            localField: "prefix_id",
            foreignField: "_id",
            as: "prefixData"
          }
        },
        {
          $addFields: {
            prefixData: { $arrayElemAt: [ "$prefixData", 0 ] }
          }
        },
        {
          $project: {
            category_id: 0,
            sticker_id: 0,
            prefix_id: 0
          }
        }
      ],
      as: "stores"
    }
  }
])

关键步骤说明:

  • 外层$match:精准筛选目标分类(_id=1),减少后续关联的数据量。
  • 外层$lookup:关联store集合,通过let传递分类ID,子pipeline中匹配store的category_id(显式类型转换避免字符串与数字不匹配的问题)。
  • 内层$lookup(sticker/prefix):在store的子流程中,分别通过sticker_id和prefix_id关联对应集合,结果以数组形式返回。
  • $addFields:使用$arrayElemAt将关联得到的数组转为单个对象(每个store仅对应一个sticker和prefix)。
  • $project(可选):移除冗余的原始ID字段,让返回结果更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 07:05:32