如何扩展MongoDB聚合管道提取refs唯一值并查询对应文档
MongoDB聚合管道扩展方案
需求实现步骤
1. 收集refs字段的所有唯一值
在现有聚合管道的输出之后,添加以下阶段提取并去重refs中的值:
方式一:$unwind + $group(直观易懂)
// 展开refs数组为单个元素 { $unwind: "$refs" }, // 分组收集唯一值 { $group: { _id: null, uniqueRefs: { $addToSet: "$refs" } } }
执行后得到包含唯一值集合的文档:
[ { "_id": null, "uniqueRefs": [1, 2, 3] } ]
方式二:$reduce + $setUnion(无需展开数组,性能更优)
// 收集所有refs数组到一个集合中 { $group: { _id: null, allRefs: { $push: "$refs" } } }, // 通过集合合并去重得到唯一值 { $project: { uniqueRefs: { $reduce: { input: "$allRefs", initialValue: [], in: { $setUnion: ["$$value", "$$this"] } } } } }
此方式同样能得到uniqueRefs: [1,2,3],且避免了数组展开操作。
2. 返回_id匹配唯一值集合的文档
在得到唯一值集合后,通过$lookup关联原集合,再提取匹配的文档:
继续添加以下聚合阶段:
// 关联原集合,匹配_id在uniqueRefs中的文档 { $lookup: { from: "yourCollection", // 替换为你的实际集合名称 localField: "uniqueRefs", foreignField: "_id", as: "matchedDocs" } }, // 展开匹配到的文档数组 { $unwind: "$matchedDocs" }, // 将匹配的文档作为根文档返回 { $replaceRoot: { newRoot: "$matchedDocs" } }
执行完成后,最终会返回原集合中_id为1、2、3的三个文档。
完整扩展后的聚合管道(以方式一为例)
// 现有聚合管道... { $unwind: "$refs" }, { $group: { _id: null, uniqueRefs: { $addToSet: "$refs" } } }, { $lookup: { from: "yourCollection", localField: "uniqueRefs", foreignField: "_id", as: "matchedDocs" } }, { $unwind: "$matchedDocs" }, { $replaceRoot: { newRoot: "$matchedDocs" } }
内容的提问来源于stack exchange,提问作者Mo B.
相关产品推荐
相关产品推荐

