如何使用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
相关产品推荐
相关产品推荐

