表:a01 数据
{ "_id" : ObjectId("6124953bc7599d3cc40d26ce"), "sam" : "001", "tof" : true}
{ "_id" : ObjectId("61249548c7599d3cc40d26cf"), "sam" : "002", "tof" : true}
{ "_id" : ObjectId("6124954ac7599d3cc40d26d0"), "sam" : "003", "tof" : true}
{ "_id" : ObjectId("6124954dc7599d3cc40d26d1"), "sam" : "004", "tof" : true}
{ "_id" : ObjectId("6124954fc7599d3cc40d26d2"), "sam" : "005", "tof" : true}

表:a02 数据
{ "_id" : ObjectId("6124953bc7599d3cc40d26ce"), "sam" : "001", "tof" : true}
{ "_id" : ObjectId("61249548c7599d3cc40d26cf"), "sam" : "002", "tof" : false}
{ "_id" : ObjectId("6124954ac7599d3cc40d26d0"), "sam" : "003", "tof" : false}
{ "_id" : ObjectId("6124954dc7599d3cc40d26d1"), "sam" : "004", "tof" : false}
{ "_id" : ObjectId("6124954fc7599d3cc40d26d2"), "sam" : "005", "tof" : true}
const mongo=require('lycq').mongo;
let dbUrl="mongodb://test:test@127.0.0.1:27017/test"
/** 
localField:在输入文档中的查找字段,这里是:app_examine_interception集合中的publish_id字段。
from:需要连接的集合,这里是:project
foreignField:需要在from集合中查找的字段
as:输出集合的名字,自定义

思路:
先使用$match确定待查询数据的范围
再使用$lookup联结另一个表,确定查询字段
最后使用$project选择需要输出的字段
*/


/**
 * [newMongoClient 用Promise封装的mongodb数据库连接函数以同步方式运行]
 * @param  {[str]} dbUrl:数据库链接
 * @return {[obj]}  [反回数据库对象]
 */
let main=async ()=>{
    let client=await mongo.newMongoClient(dbUrl);
    let a01=client.collection("a01");
    let a02=client.collection("a02");

    let match={tof:true} //先对数据进行第一次过滤
    let lookup={
        from:"a02", //from:需要连接的集合,这里是:a02
        localField:'sam', // localField:在输入文档中的查找字段,这里是a01表的 sam 字段。相当于主键
        foreignField:'sam',  // foreignField:需要在from集合中查找的字段  相当于是外键。
        as:"lxy" // as:输出集合的名字,自定义
    }
    let project={'sam':1,'tof':1,arr:"$lxy.tof"} //对得到的关联结果进行结构重构。
    let unwind="$arr" //将输出的数据进行分组
    let match2={arr:true} // 对分组后的数据进行第二次过滤 .注意这里的arr是拆组前重新定义的字段,原来2个表是没有这个字段的

    let doc=await a01.aggregate([{$lookup:lookup}, {$project:project}, {$unwind:unwind}, {$match:match2}]).toArray();
    // console.log(doc);

    for(let i=0;i<doc.length;i++){
        console.log(JSON.stringify(doc[i]));
    }
}
main();


输出结果:
{"_id":"61249548c7599d3cc40d26cf","sam":"002","tof":true,"arr":true}
{"_id":"6124954fc7599d3cc40d26d2","sam":"005","tof":true,"arr":true}


查找不匹配的,用下面的写法
    let doc2=await a01.aggregate([
        {$lookup:{
                from:"a02",
                localField: "sam",
                foreignField:"sam",
                as:"lxy"
            }},
        {$match:{"lxy":[]}},
        { $project: {"sam":1}}
    ]).toArray();

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐