Mongodb $lookup 用法简单介绍

$lookup  是 Mongodb 3.2版本 新增的聚合框架中的一种查询方式; 主要用来实现多表链接查询; 相当关系型数据库中多表链接查询。

一、基本语法及主要功能

1. 主要功能 是将每个输入待处理的文档,经过$lookup 阶段的处理,输出的新文档中会包含一个新生成的数组列(户名可根据需要命名新key的名字 )。数组列存放的数据 是 来自 被Join 集合的适配文档,如果没有,集合为空(即 为[ ])

2.主要语法:

  db.collection.aggregate([{
        $lookup: {
               from: "<collection to join>",
               localField: "<field from the input documents>",
               foreignField: "<field from the documents of the from collection>",
               as: "<output array field>"
             }
    })

  

3.语法的解释说明

语法值 解释说明
from
同一个数据库下等待被Join的集合。
localField

源集合中的match值,如果输入的集合中,某文档没有 localField

这个Key(Field),在处理的过程中,会默认为此文档含

有 localField:null的键值对。

foreignField
待Join的集合的match值,如果待Join的集合中,文档没有foreignField
值,在处理的过程中,会默认为此文档含有 foreignField:null的键值对。
as
为输出文档的新增值命名。如果输入的集合中已存在该值,则会覆盖掉,

 

二、两张表关联查询

1.测试数据准备

db.Customer.insert({customerCode:1,name:"customer1",phone:"13112345678",address:"test1"})

db.Customer.insert({customerCode:2,name:"customer2",phone:"13112345679",address:"test2"})

db.Order.insert({orderId:1,orderCode:"order001",customerCode:1,price:200})

db.Order.insert({orderId:2,orderCode:"order002",customerCode:2,price:400})

2. $lookup 查询两张表

db.Customer.aggregate(
    [{        $lookup: {
           from: "Order",
           localField: "customerId",
           foreignField: "customerId",
           as: "customerOder"
         }
    } 
    ])

效果如下:

 

 

 $lookup 中的as:"customerOrder"  聚合为 一个数组类型字段

 

三、三张表关联查询

1.准备数据

db.Customer.insert({customerCode:1,name:"customer1",phone:"13112345678",address:"test1"})

db.Customer.insert({customerCode:2,name:"customer2",phone:"13112345679",address:"test2"})

db.Order.insert({orderId:1,orderCode:"order001",customerCode:1,price:200})

db.Order.insert({orderId:2,orderCode:"order002",customerCode:2,price:400})

db.orderItem.insert({itemId:1,productName:"apples",qutity:2,orderId:1})
db.orderItem.insert({itemId:2,productName:"oranges",qutity:2,orderId:1})
db.orderItem.insert({itemId:3,productName:"mangoes",qutity:2,orderId:1})

db.orderItem.insert({itemId:4,productName:"apples",qutity:2,orderId:2})
db.orderItem.insert({itemId:5,productName:"oranges",qutity:2,orderId:2})
db.orderItem.insert({itemId:6,productName:"mangoes",qutity:2,orderId:2})

2.$lookup 查询三张表

    db.Order.aggregate([{
        $lookup: {
               from: "Customer",
               localField: "customerCode",
               foreignField: "customerCode",
               as: "curstomer"
             }
        
    },
    {
        $lookup: {
               from: "orderItem",
               localField: "orderId",
               foreignField: "orderId",
               as: "orderItem"
             }
    }
    }]
     

效果如下:

 

 $lookup 中的as:"customerOrder"  聚合为 一个数组类型字段

$lookup 中的as:"orderItem"  聚合为 一个数组类型字段

 

由此可见,关联多少个人表,就可以使用多少个$lookup来做关联;

至此 $lookup 简单用法介绍完毕!

 

1.测试数据准备

posted @ 2021-07-26 14:16  Howard见贤思齐  阅读(3233)  评论(0)    收藏  举报