经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MongoDB » 查看文章
详解MongoDB中的多表关联查询($lookup)
来源:cnblogs  作者:东山絮柳仔  时间:2018/12/3 9:59:16  对本文有异议

一.  聚合框架 

聚合框架是MongoDB的高级查询语言,它允许我们通过转换和合并多个文档中的数据来生成新的单个文档中不存在的信息。

聚合管道操作主要包含下面几个部分:

命令 功能描述
$project 指定输出文档里的字段.
$match 选择要处理的文档,与fine()类似。
$limit 限制传递给下一步的文档数量。
$skip 跳过一定数量的文档。
$unwind 扩展数组,为每个数组入口生成一个输出文档。
$group 根据key来分组文档。
$sort 排序文档。
$geoNear 选择某个地理位置附近的的文档。
$out 把管道的结果写入某个集合。
$redact 控制特定数据的访问。

$lookup

多表关联(3.2版本新增)

在本篇幅中,我们聚焦$lookup的使用。

二.  $lookup的功能及语法

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

2. 基本语法

  1. {
  2. $lookup:
  3. {
  4. from: <collection to join>,
  5. localField: <field from the input documents>,
  6. foreignField: <field from the documents of the "from" collection>,
  7. as: <output array field>
  8. }
  9. }

 3. 语法的解释说明

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

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

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

有 localField:null的键值对。

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

 

(注:null = null 此为真)

其语法功能类似于下面的伪SQL语句:

  1. SELECT *, <output array field>
  2. FROM collection
  3. WHERE <output array field> IN (SELECT *
  4. FROM <collection to join>
  5. WHERE <foreignField>= <collection.localField>);

 

三. 案例

以上的语法介绍有些枯燥,不易理解,我们直接分析品味案例好了。

假设 有 订单集合, 存储的测试数据 如下:

  1. db.orders.insert([
  2. { "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
  3. { "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
  4. { "_id" : 3 }
  5. ])

其中 item 对应 数据为 商品名称

另外 一个 就是就是 商品库存集合 ,存储的测试数据 如下:

  1. db.inventory.insert([
  2. { "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
  3. { "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
  4. { "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
  5. { "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
  6. { "_id" : 5, "sku": null, description: "Incomplete" },
  7. { "_id" : 6 }
  8. ])

此集合中的 sku 数据等同于 订单 集合中的 商品名称

在这种模式设计下,如果要查询订单表对应商品的库存情况,应如何写代码呢?

很明显这需要两个集合Join。

场景简单,不做赘述,直送答案 。其语句 如下:

  1. db.orders.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "inventory",
  6. localField: "item",
  7. foreignField: "sku",
  8. as: "inventory_docs"
  9. }
  10. }
  11. ])

返回的执行结果如下:

  1. {
  2. "_id" : NumberInt("1"),
  3. "item" : "almonds",
  4. "price" : NumberInt("12"),
  5. "quantity" : NumberInt("2"),
  6. "inventory_docs" : [
  7. {
  8. "_id" : NumberInt("1"),
  9. "sku" : "almonds",
  10. "description" : "product 1",
  11. "instock" : NumberInt("120")
  12. }
  13. ]
  14. }
  15. {
  16. "_id" : NumberInt("2"),
  17. "item" : "pecans",
  18. "price" : NumberInt("20"),
  19. "quantity" : NumberInt("1"),
  20. "inventory_docs" : [
  21. {
  22. "_id" : NumberInt("4"),
  23. "sku" : "pecans",
  24. "description" : "product 4",
  25. "instock" : NumberInt("70")
  26. }
  27. ]
  28. }
  29. {
  30. "_id" : NumberInt("3"),
  31. "inventory_docs" : [
  32. {
  33. "_id" : NumberInt("5"),
  34. "sku" : null,
  35. "description" : "Incomplete"
  36. },
  37. {
  38. "_id" : NumberInt("6")
  39. }
  40. ]
  41. }

 

分析查询语句和结果,回扣$lookup定义,可以将上面的处理过程,描述如下:

从集合order中逐个获取文档处理,拿到一个文档后,会根据localField 值 遍历 被 Join的 inventory集合(from: "inventory"),看inventory集合文档中 foreignField值是否与之相等。如果相等,就把符合条件的inventory文档  整体 内嵌到聚合框架新生成的文档中,并且新key 统一命名为 inventory_docs。考虑到符合条件的文档不唯一,这个Key对应的Value是个数组形式。原集合中Key对应的值为Null值或不存在时,需特别小心。

四. 说明

在以下的说明中,为描述方便,将 from对应的集合定义为 被join集合;待聚合的表成为源表; 将 localField 和 foreignField 对应的Key 定义 比较列。

1. 因客户端工具显示的问题,上面示例中查询结果重Int 类型值都自动显示为了 NumberInt("")。这个NumberInt标注,请忽略,不影响我们的功能测试。

2. 这个示例中,一共输出了三个文档,在没有再次聚合($match)的条件下,这个输出文档数量是以输入文档的数量来决定的(由order来决定),而不是以被Join的集合(inventory)文档数量决定。

3. 在此需要特别强调的是输出的第三个文档。在源库中原文档没有要比较的列(即item值不存在,既不是Null值,也不是值为空),此时 和 被Join 集合比较,如果 被Join集合中 比较列 也恰好 为NUll 或 不存在的值,此时,判断相等 ,即会把 被Join集合中 比较列 为NUll 或 值不存在 文档 吸收进来。

4. 假设 源表(order) 中比较列 为某一个值,而此值在待比较表(inventory)的所有文档中都不存在,那么查询结果会是什么样子呢?

order 集合在现有数据的基础上,再被insert 进一笔测试数据,这个订单的商品为 Start,在库存商品中根本没有此数据。

  1. db.orders.insert({"_id" : 4, "item" : "Start", "price" : 2000, "quantity" : 1 })

order集合的文档数量由之前的3个增长为4个。

再次执行查询

  1. db.orders.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "inventory",
  6. localField: "item",
  7. foreignField: "sku",
  8. as: "inventory_docs"
  9. }
  10. }
  11. ])

此时查看结果 

  1. {
  2. "_id" : NumberInt("1"),
  3. "item" : "almonds",
  4. "price" : NumberInt("12"),
  5. "quantity" : NumberInt("2"),
  6. "inventory_docs" : [
  7. {
  8. "_id" : NumberInt("1"),
  9. "sku" : "almonds",
  10. "description" : "product 1",
  11. "instock" : NumberInt("120")
  12. }
  13. ]
  14. }
  15. {
  16. "_id" : NumberInt("2"),
  17. "item" : "pecans",
  18. "price" : NumberInt("20"),
  19. "quantity" : NumberInt("1"),
  20. "inventory_docs" : [
  21. {
  22. "_id" : NumberInt("4"),
  23. "sku" : "pecans",
  24. "description" : "product 4",
  25. "instock" : NumberInt("70")
  26. }
  27. ]
  28. }
  29. {
  30. "_id" : NumberInt("3"),
  31. "inventory_docs" : [
  32. {
  33. "_id" : NumberInt("5"),
  34. "sku" : null,
  35. "description" : "Incomplete"
  36. },
  37. {
  38. "_id" : NumberInt("6")
  39. }
  40. ]
  41. }
  42. {
  43. "_id" : NumberInt("4"),
  44. "item" : "Start",
  45. "price" : NumberInt("2000"),
  46. "quantity" : NumberInt("1"),
  47. "inventory_docs" : [ ]
  48. }

 查询出的结果也由之前的3个变成了4个。比较特别的是第四个文档 ,其新增列 为 "inventory_docs" : [ ] ,即值为空 。所以,此时,实现的功能非常像关系型数据库的 left join。

那么,可不可以只筛选出新增列为空的文档呢

即 我们查询出 ,比较列的条件下,刷选出只在A集合中,而不在集合B的文档呢? 就像关系数据库中量表Join的 left join on a.key =b.key where b.key is null .

答案是可以的

其实回到聚合框架上来,再次聚合一下就可以了,来一次$match就可以了。

执行的语句调整一下就OK了。

  1. db.orders.aggregate([
  2. {
  3. $lookup:
  4. {
  5. from: "inventory",
  6. localField: "item",
  7. foreignField: "sku",
  8. as: "inventory_docs"
  9. }
  10. },
  11. { $match : {"inventory_docs" : [ ]} }
  12. ])

执行结果 为 

  1. {
  2. "_id" : NumberInt("4"),
  3. "item" : "Start",
  4. "price" : NumberInt("2000"),
  5. "quantity" : NumberInt("1"),
  6. "inventory_docs" : [ ]
  7. }

可以看出执行结果只有一个文档。这个文档表明的含义是:订单中有这个商品,但是库存中没有这个商品。

$look只是聚合框架的一个stage,在其前前后后,都可以嵌入到其他的聚合管道的命令,例如$match.$group等。下面的说明5,也可以说明一二)

5. 以上的比较列都是单一的Key/Value,如果复杂一点,如果比较的列是数组,我们又该如何关联呢?

我们接下来再来测试一把。将之前 集合order 、inventory 插入的数据清空。

插入此场景下的新数据,向order中插入的数据,如下:

  1. db.orders.insert({ "_id" : 1, "item" : "MON1003", "price" : 350, "quantity" : 2, "specs" :[ "27 inch", "Retina display", "1920x1080" ], "type" : "Monitor" })
  1. specs 对应的value是数组格式。

向集合inventory 新插入的数据 如下:

  1. db.inventory.insert({ "_id" : 1, "sku" : "MON1003", "type" : "Monitor", "instock" : 120,"size" : "27 inch", "resolution" : "1920x1080" })
  2. db.inventory.insert({ "_id" : 2, "sku" : "MON1012", "type" : "Monitor", "instock" : 85,"size" : "23 inch", "resolution" : "1280x800" })
  3. db.inventory.insert({ "_id" : 3, "sku" : "MON1031", "type" : "Monitor", "instock" : 60,"size" : "23 inch", "display_type" : "LED" })

查询的语句如下:

  1. db.orders.aggregate([
  2. {
  3. $unwind: "$specs"
  4. },
  5. {
  6. $lookup:
  7. {
  8. from: "inventory",
  9. localField: "specs",
  10. foreignField: "size",
  11. as: "inventory_docs"
  12. }
  13. },
  14. {
  15. $match: { "inventory_docs": { $ne: [] } }
  16. }
  17. ])

查询显示结果如下:

  1. {
  2. "_id" : NumberInt("1"),
  3. "item" : "MON1003",
  4. "price" : NumberInt("350"),
  5. "quantity" : NumberInt("2"),
  6. "specs" : "27 inch",
  7. "type" : "Monitor",
  8. "inventory_docs" : [
  9. {
  10. "_id" : NumberInt("1"),
  11. "sku" : "MON1003",
  12. "type" : "Monitor",
  13. "instock" : NumberInt("120"),
  14. "size" : "27 inch",
  15. "resolution" : "1920x1080"
  16. }
  17. ]
  18. }

仔细看啊,输出文档中的 specs 对应的数据变成了字符串类型(原集合为数组)。是什么发挥了如此神奇功效???,请看黑板,请将目光集中在

  1. {
  2. $unwind: "$specs"
  3. }

还有个小问题,大家猜一下,如果查询语句中没有

  1. {
  2. $match: { "inventory_docs": { $ne: [] } }
  3. }

    结果会是什么样呢?即查看语句修改为:
  1. db.orders.aggregate([
  2. {
  3. $unwind: "$specs"
  4. },
  5. {
  6. $lookup:
  7. {
  8. from: "inventory",
  9. localField: "specs",
  10. foreignField: "size",
  11. as: "inventory_docs"
  12. }
  13. }
  14. ])

大家猜猜看!

大家猜猜看!

大家猜猜看!

呵呵...此时的结果是:

  1. 文档1
  2. {
  3. "_id" : NumberInt("1"),
  4. "item" : "MON1003",
  5. "price" : NumberInt("350"),
  6. "quantity" : NumberInt("2"),
  7. "specs" : "27 inch",
  8. "type" : "Monitor",
  9. "inventory_docs" : [
  10. {
  11. "_id" : NumberInt("1"),
  12. "sku" : "MON1003",
  13. "type" : "Monitor",
  14. "instock" : NumberInt("120"),
  15. "size" : "27 inch",
  16. "resolution" : "1920x1080"
  17. }
  18. ]
  19. }
  20. 文档2
  21. {
  22. "_id" : NumberInt("1"),
  23. "item" : "MON1003",
  24. "price" : NumberInt("350"),
  25. "quantity" : NumberInt("2"),
  26. "specs" : "Retina display",
  27. "type" : "Monitor",
  28. "inventory_docs" : [ ]
  29. }
  30. 文档3
  31. {
  32. "_id" : NumberInt("1"),
  33. "item" : "MON1003",
  34. "price" : NumberInt("350"),
  35. "quantity" : NumberInt("2"),
  36. "specs" : "1920x1080",
  37. "type" : "Monitor",
  38. "inventory_docs" : [ ]
  39. }

你推算出正确结果了吗?

谢谢!!!

希望以上的讲解和演示能对大家学习$lookup有所帮助。

 

 

注:以上案例数据参考MongoDB官方网站,大家也可访问官网获取更多、更全的相关知识。

 

本文版权归作者所有,未经作者同意不得转载,谢谢配合!!!



 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号