如何使用MongoDB聚合操作实现同文档内两个数组的自关联查询
聚合操作实现方案
你可以直接使用以下MongoDB聚合管道完成需求:
db.collection.aggregate([ // 将propertyB转为以group为键的映射对象,方便快速匹配 { $addFields: { groupCountMap: { $arrayToObject: { $map: { input: "$propertyB", as: "b", in: { k: "$$b.group", v: "$$b.numberOfTimes" } } } } } }, // 拆分propertyA数组为单个文档做逐行处理 { $unwind: "$propertyA" }, // 给每个propertyA元素追加匹配到的numberOfTimes字段 { $addFields: { "propertyA.numberOfTimes": { $getField: { field: { $toString: "$propertyA.group" }, input: "$groupCountMap" } } } }, // 将处理后的元素重组为result数组 { $group: { _id: "$_id", result: { $push: "$propertyA" } } }, // 移除不需要的_id字段 { $project: { _id: 0 } } ])
核心用到的聚合操作符说明
$arrayToObject:将数组转为键值对对象,提升匹配效率,避免额外关联查询的性能消耗$unwind:拆分数组字段为单条记录,方便逐行处理字段$getField:根据group键名从映射对象中快速取出对应的numberOfTimes值$group+$push:将处理后的单条记录重新合并为最终的result数组
内容的提问来源于stack exchange,提问作者Neville Bamshoot
相关产品推荐
相关产品推荐

