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

求MongoDB多集合嵌套关联查询语句(含4个集合示例)

MongoDB 多集合嵌套关联查询实现

需求说明

需要关联customer、order、orderDeatils、products四个集合,查询出包含订单基础信息、客户详情及关联商品列表的结果,期望输出格式如下:

{ 
  orderId: "123", 
  date: "05-01-2024", 
  customerId: "1232", 
  customerName: "name A", 
  customerEmail: "nameA@gmail.com", 
  productsList : [
    [
      { productId: "123", name: "mobile A", quantity : 2 },
      { productId: "124", name: "mobile B", quantity : 3 }
    ]
  ] 
}

聚合查询语句

db.order.aggregate([
  // 关联客户集合,获取客户信息
  {
    $lookup: {
      from: "customer",
      localField: "customerId",
      foreignField: "customerId",
      as: "customerInfo"
    }
  },
  // 展开客户信息数组(单订单对应单客户)
  { $unwind: "$customerInfo" },
  // 关联订单明细集合
  {
    $lookup: {
      from: "orderDeatils",
      localField: "orderId",
      foreignField: "orderId",
      as: "orderDetails"
    }
  },
  // 关联商品集合,获取商品基础信息
  {
    $lookup: {
      from: "products",
      localField: "orderDetails.productId",
      foreignField: "productId",
      as: "products"
    }
  },
  // 合并商品信息与对应订单数量
  {
    $addFields: {
      productsList: {
        $map: {
          input: "$orderDetails",
          as: "detail",
          in: {
            $mergeObjects: [
              { $arrayElemAt: ["$products", { $indexOfArray: ["$products.productId", "$$detail.productId"] }] },
              { quantity: "$$detail.quantity" }
            ]
          }
        }
      }
    }
  },
  // 整理输出字段,匹配期望格式
  {
    $project: {
      _id: 0,
      orderId: 1,
      date: 1,
      customerId: 1,
      customerName: "$customerInfo.name",
      customerEmail: "$customerInfo.email",
      productsList: { $push: "$productsList" }
    }
  }
])

语句解析

  • 关联客户信息:通过customerId将订单与customer集合关联,用$unwind展开单客户数组,方便提取客户名称、邮箱字段
  • 关联订单明细与商品:先通过orderId获取当前订单的所有明细,再通过明细中的productId关联products集合拿到商品基础信息
  • 合并商品与数量:使用$map遍历订单明细,将对应商品信息与数量字段合并,生成完整的商品条目
  • 格式化输出:通过$project筛选并重命名字段,同时将商品列表包装为二维数组,匹配需求中的输出结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:12:36