MongoDB $lookup联表查询

入手MongoDB第一天,发现跟关系型数据库差别也不算太大。比较有意思的是$lookup联表查询。

自己总结了一下,比较土,但是易于理解。(好多资料都是直接复制官方文档原话。)

{$lookup:
      {
            from:'products', //关联你需要查询的表2
            localField:'product_id', //指定表1中的一个关键字段对应第三个参数
            foreignField:'_id',  //指定表2中的一个关键字段对应第二个参数
            as:'orderLists'  //查询时,当第二个参数满足第一个参数,则将集合添加进orderlists
      }
}

加几条数据试试!

orders表:

{
    "_id" : 1,
    "product_id" : 154,
    "status" : 1
}

{
    "_id" : 2,
    "product_id" : 155,
    "status" : 1
}

products表:

{
    "_id" : 154,
    "name" : "笔记本电脑"
}
{
    "_id" : 155,
    "name" : "耳机"
}
{
    "_id" : 156,
    "name" : "台式电脑"
}

来查一下:用的Node.js语法,都大同小异。

const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, { useNewUrlParser: true }, function (err, db) {
    if (err) throw err;
    console.log("runoob库已创建!")

    var dbo = db.db("runoob");
    
 
    dbo.collection("orders").aggregate([
        {$lookup:
            {
                from:'products', //关联查询表2
                localField:'product_id', //关联表1的商品编号ID
                foreignField:'_id',  //匹配表2中的ID与关联表1商品编号ID对应
                as:'orderLists'  //满足 localField与foreignField的信息加入orderlists集合
            }
        },
        {$match:{"product_id":154}}//筛选类似与SQL的where
    ]).toArray(function(err,res){
        if(err)throw err;
        console.log(JSON.stringify(res))
        db.close()
    })
   
})

最后得出的结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值