You need to enable JavaScript to run this app. 如何在MongoDB中对数组对象使用$lookup实现跨集合关联查询
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中对数组对象使用$lookup实现跨集合关联查询

MongoDB 数组元素关联查询填充方案

stockIn 集合示例文档结构:

{
  "_id": ObjectId("60d21b4667d0d8992e610c85"),
  "stockInCode": "IN202405001",
  "inTime": ISODate("2024-05-20T10:00:00Z"),
  "productInTransation": [
    {"productId": ObjectId("60d21b2267d0d8992e610c7f"), "inQty": 100, "batchNo": "P202405001"},
    {"productId": ObjectId("60d21b3167d0d8992e610c82"), "inQty": 50, "batchNo": "P202405002"}
  ]
}

products 集合示例文档结构:

{
  "_id": ObjectId("60d21b2267d0d8992e610c7f"),
  "productName": "USB-C充电线",
  "spec": "1m 白色",
  "unit": "条",
  "price": 9.9
}

高版本简洁写法(兼容 MongoDB 3.6+)

直接通过 $lookup 关联后用 $map 匹配对应商品信息,无需拆分数组再合并:

db.stockIn.aggregate([
  // 关联products集合,拉取所有关联的商品数据存入临时字段
  {
    $lookup: {
      from: "products",
      localField: "productInTransation.productId",
      foreignField: "_id",
      as: "tempProductList"
    }
  },
  // 遍历商品入库数组,给每个元素挂载对应的商品详情
  {
    $addFields: {
      productInTransation: {
        $map: {
          input: "$productInTransation",
          as: "inItem",
          in: {
            // 合并原有入库字段+新增的product详情字段
            $mergeObjects: [
              "$$inItem",
              {
                product: {
                  // 匹配到对应productId的商品信息
                  $first: {
                    $filter: {
                      input: "$tempProductList",
                      cond: { $eq: ["$$this._id", "$$inItem.productId"] }
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  },
  // 删除临时存储的商品列表字段
  { $unset: "tempProductList" }
])

低版本兼容写法(兼容 MongoDB 3.4及以下)

如果使用的MongoDB版本较低,不支持$mergeObjects/$first等语法,可以用拆分再分组的方式实现:

db.stockIn.aggregate([
  // 拆分数组为单条记录
  { $unwind: "$productInTransation" },
  // 单条记录关联对应商品
  {
    $lookup: {
      from: "products",
      localField: "productInTransation.productId",
      foreignField: "_id",
      as: "productInTransation.product"
    }
  },
  // 把关联返回的数组转为单个对象
  { $unwind: "$productInTransation.product" },
  // 按入库单ID分组,重新合并为数组,保留原有入库单字段
  {
    $group: {
      _id: "$_id",
      stockInCode: { $first: "$stockInCode" },
      inTime: { $first: "$inTime" },
      productInTransation: { $push: "$productInTransation" }
      // 其余入库单自定义字段都可以用$first操作符保留
    }
  }
])

返回结果示例

执行查询后,每个productInTransation数组元素都会新增product字段存储对应商品完整信息:

{
  "_id": ObjectId("60d21b4667d0d8992e610c85"),
  "stockInCode": "IN202405001",
  "inTime": ISODate("2024-05-20T10:00:00Z"),
  "productInTransation": [
    {
      "productId": ObjectId("60d21b2267d0d8992e610c7f"),
      "inQty": 100,
      "batchNo": "P202405001",
      "product": {
        "_id": ObjectId("60d21b2267d0d8992e610c7f"),
        "productName": "USB-C充电线",
        "spec": "1m 白色",
        "unit": "条",
        "price": 9.9
      }
    },
    {
      "productId": ObjectId("60d21b3167d0d8992e610c82"),
      "inQty": 50,
      "batchNo": "P202405002",
      "product": {
        "_id": ObjectId("60d21b3167d0d8992e610c82"),
        "productName": "无线鼠标",
        "spec": "黑色 静音版",
        "unit": "个",
        "price": 29.9
      }
    }
  ]
}

内容的提问来源于stack exchange,提问作者silvester landu hunggu wali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 19:36:03