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

如何使用MongoDB聚合按关联键合并数组并新增riskControls字段

MongoDB 按关联条件合并两个数组并生成新字段实现方案

核心需求

将文档内risks数组与controls数组按关联关系合并为新的riskControls数组:

  • risks元素的_id与controls元素的links.entity.valueKey为关联字段
  • 每个risk元素携带所有匹配的controls作为子字段
  • 所有未匹配到任何risk的controls统一放在数组末尾的单独元素内

完整聚合语句

db.collection.aggregate([
  {
    $addFields: {
      // 给每个risk匹配对应的controls
      processedRisks: {
        $map: {
          input: "$risks",
          as: "risk",
          in: {
            $mergeObjects: [
              "$$risk",
              {
                controls: {
                  $filter: {
                    input: "$controls",
                    as: "control",
                    cond: {
                      $in: ["$$risk._id", "$$control.links.entity.valueKey"]
                    }
                  }
                }
              }
            ]
          }
        }
      },
      // 收集所有匹配过risk的control唯一标识,用于后续筛选未匹配项
      matchedControlIds: {
        $reduce: {
          input: "$risks",
          initialValue: [],
          in: {
            $setUnion: [
              "$$value",
              {
                $map: {
                  input: {
                    $filter: {
                      input: "$controls",
                      as: "control",
                      cond: { $in: ["$$this._id", "$$control.links.entity.valueKey"] }
                    }
                  },
                  in: "$$this.identifier"
                }
              }
            ]
          }
        }
      }
    }
  },
  {
    $addFields: {
      // 合并带关联的风险条目与无匹配的管控条目,生成最终字段
      riskControls: {
        $concatArrays: [
          "$processedRisks",
          [
            {
              controls: {
                $filter: {
                  input: "$controls",
                  as: "control",
                  cond: { $not: { $in: ["$$control.identifier", "$matchedControlIds"] } }
                }
              }
            }
          ]
        ]
      }
    }
  },
  // 清理临时字段与原始数组字段,保留需要的输出内容
  {
    $project: {
      key: 1,
      riskControls: 1,
      _id: 0
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 21:27:01