如何在MongoDB中实现多字段匹配的Lookup联表查询?
MongoDB多字段匹配的$lookup联表查询实现
要实现你需要的多字段关联查询,MongoDB 3.6及以上版本支持在$lookup中使用自定义聚合管道(pipeline参数)来实现多条件匹配,替代默认的单字段关联。以下是针对你的需求的具体实现方案:
基础查询(左连接,类似SQL LEFT JOIN)
从collection_1出发,关联collection_2并匹配两个条件:
db.collection_1.aggregate([ { $lookup: { from: "collection_2", // 定义要传递到子管道的当前集合字段变量 let: { collection1_id: "$_id", collection1_stage: "$stage_id" }, // 子管道中编写多条件匹配逻辑 pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$collection_1_id", "$$collection1_id"] }, { $eq: ["$stage_id", "$$collection1_stage"] } ] } } } ], // 关联结果存储到该字段中 as: "matched_collection_2" } } ])
内连接(类似SQL INNER JOIN)
如果只需要返回两边都匹配到的文档,可以在$lookup之后添加$match过滤掉未匹配到的结果:
db.collection_1.aggregate([ { $lookup: { from: "collection_2", let: { collection1_id: "$_id", collection1_stage: "$stage_id" }, pipeline: [ { $match: { $expr: { $and: [ { $eq: ["$collection_1_id", "$$collection1_id"] }, { $eq: ["$stage_id", "$$collection1_stage"] } ] } } } ], as: "matched_collection_2" } }, // 过滤掉没有匹配到collection_2的文档 { $match: { "matched_collection_2": { $ne: [] } } } ])
结果说明
执行上述查询后,每个collection_1的文档会新增一个matched_collection_2数组字段,里面包含所有满足两个匹配条件的collection_2文档。如果是内连接版本,只会返回有匹配结果的collection_1文档。
内容的提问来源于stack exchange,提问作者Nisarg Soni
相关产品推荐
相关产品推荐

