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

如何为MongoDB关联查询结果添加对应quantity字段?

解决MongoDB聚合中为关联商品添加对应购买数量的问题

你需要调整$lookup的参数和子管道逻辑,把订单的lineItems完整传入子管道,再匹配对应商品的购买数量,具体修改后的聚合管道如下:

const orderPipeline = [
  {
    $match: { customerId: 'the customer\'s ID' },
  },
  {
    $lookup: {
      from: 'products',
      let: { orderLineItems: '$lineItems' }, // 传入完整的lineItems数组
      pipeline: [
        { 
          $match: { 
            $expr: { 
              $in: ['$productId', '$$orderLineItems.productId'] 
            } 
          } 
        },
        {
          $addFields: {
            // 从传入的lineItems中筛选出当前商品对应的条目,取出quantity
            quantity: {
              $arrayElemAt: [
                {
                  $map: {
                    input: {
                      $filter: {
                        input: '$$orderLineItems',
                        cond: { $eq: ['$$this.productId', '$productId'] }
                      }
                    },
                    as: 'item',
                    in: '$$item.quantity'
                  }
                },
                0
              ]
            }
          }
        }
      ],
      as: 'products',
    },
  },
  { $unset: ['lineItems'] },
];

关键改动说明:

  1. let参数调整:不再只传递productIds,而是传入整个lineItems数组,让子管道能获取到每个商品对应的购买数量。
  2. 子管道添加$addFields阶段:
    • 先用$filter从lineItems中筛选出与当前商品productId匹配的条目;
    • 再用$map提取筛选结果中的quantity值;
    • 最后用$arrayElemAt取出数组中的唯一元素(每个productId在lineItems中只会出现一次),赋值给商品文档的quantity字段。

处理后,products数组中的每个商品文档都会带上对应的购买数量,同时原来的lineItems字段会被移除,完全符合需求。

内容的提问来源于stack exchange,提问作者xandert.93

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:55:22