MongoDB聚合查询:将frame_id字段移入数组每个元素中
解决方案
你可以在现有聚合管道的末尾添加$set(或$addFields)阶段,通过$map操作符遍历sections数组,将当前文档的frame_id注入到数组的每个元素中,再用$project移除顶层的frame_id字段。
修改后的完整聚合查询如下:
db['foo'].aggregate([ { $project: { frame: { frame_id: "$frameProfileId", sections: { $filter: { input: "$sections", cond: { $eq: [ "$$frameSection.metadata.subType", "Quaternion"] }, as: "frameSection" } } } }}, { $unwind: "$frame"}, { $replaceRoot: { newRoot: "$frame"}}, // 新增:给sections每个元素添加frame_id { $set: { sections: { $map: { input: "$sections", as: "item", in: { $mergeObjects: [ "$$item", { frame_id: "$frame_id" } ] } } } }}, // 移除顶层冗余的frame_id { $project: { frame_id: 0 }} ])
关键逻辑说明:
$map遍历数组:逐个处理sections里的元素,用$mergeObjects把原元素和frame_id字段合并,避免手动列举所有字段的麻烦,后续元素新增字段也能自动兼容。$project清理字段:最后剔除顶层的frame_id,只保留处理后的sections数组结构。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

