首页  编辑  

多表关联查询

Tags: /Node & JS/   Date Created:
Mongodb 中,有A,B两个Collection, 如何实现下面的效果:
select A.name, A.scd, A.vcd, B.desc
left join B on A.scd=B.scd and A.vcd = B.vcd 
where now between A.start and A.end  and A.scd = "SCD" and A.name= "ABCD"
      and now between B.start and B.end and B.enabled=true and B.param = "xxxx"
等价Mongo查询:
db.A.aggregate([
    {
        $lookup: {
            from: "B",
            let: { scd: "$scd", vcd: "$vcd" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: ["$enabled", true] },
                                { $eq: ["$vcd", "$$vcd"] },
                                { $eq: ["$scd", "$$scd"] },
                                { $eq: ["$param", "xxxx"] },
                                { $lte: ["$start", ISODate("2024-04-18 10:26:34")] },
                                { $gte: ["$end", ISODate("2024-04-18 10:26:34")] }
                            ]
                        }
                    }
                }
            ],
            as: "B"
        }
    },
    {
        $match: {
            $and: [
                { "name": "ABCD" },
                { "scd": "SCD" },
                { "start": { $lte : ISODate("2024-04-18 10:26:34") } },
                { "end": { $gte : ISODate("2024-04-18 10:26:34") } },
                { "B": { $ne: [] } } // Ensure there is a match in B
            ]
        }
    },
    {
        $project: {
            name: "$name",
            scd: "$scd",
            vcd: "$vcd",
            pcd: "$pcd",
            desc: {$arrayElemAt: ["$B.desc", 0]},
            // B: { $arrayElemAt: ["$B", 0] } // Assuming there's only one matching document in B
        }
    }
]);