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

MongoDB投影中如何向匹配的对象数组添加特定字段

解决方案

要实现将documents.orderData.productIds.quantity匹配到对应documents.productData对象中,你可以在聚合查询的末尾添加一个$addFields(或整合到现有$project)阶段,通过$map+$filter+$mergeObjects组合完成字段合并:

核心聚合阶段代码

{
  $addFields: {
    "documents.productData": {
      $map: {
        input: "$documents.productData",
        as: "product",
        in: {
          $mergeObjects: [
            "$$product",
            {
              quantity: {
                $getField: {
                  field: "quantity",
                  input: {
                    $first: {
                      $filter: {
                        input: "$documents.orderData.productIds",
                        cond: { $eq: ["$$this.id", "$$product._id"] }
                      }
                    }
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

代码说明

  1. $map:遍历documents.productData中的每个产品对象
  2. $filter:从documents.orderData.productIds中筛选出id与当前产品_id匹配的条目
  3. $first:取出筛选结果的第一个条目(因为你明确两者是一一匹配关系)
  4. $getField:提取匹配条目中的quantity字段
  5. $mergeObjects:将原产品对象与新增的quantity字段合并,保留原有字段的同时添加新数据

边界处理(可选)

如果存在产品未匹配到对应quantity的情况,可以用$ifNull设置默认值:

quantity: {
  $ifNull: [
    {
      $getField: {
        field: "quantity",
        input: {
          $first: {
            $filter: {
              input: "$documents.orderData.productIds",
              cond: { $eq: ["$$this.id", "$$product._id"] }
            }
          }
        }
      }
    },
    0 // 这里可以替换为你需要的默认值,比如null或空字符串
  ]
}

使用方式

将这个$addFields阶段插入到你的聚合查询的最后位置——确保它在已经关联得到documents.orderData和documents.productData的阶段之后执行。如果你的原查询最后是$project阶段,也可以直接把documents.productData的处理逻辑整合到$project中,效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:29:58