小小这次进行实记,这次是关于MongoDB的多表连接查询,使用此连接查询,实现MySql中的order与having等方法。
MongoDB 多表关联查询
这里使用的是MongoDB的多表关联查询。
聚合框架
聚合框架是MongoDB的高级查询语言,允许我们通过转换和合并多个文档中的数据,用于相关的指定。
在本篇中,将会着重的介绍lookup的相关使用。
$lookup 的功能以及语法
主要功能
这里主要功能,是用于输入待处理的文档,经过lookup阶段的处理,将会输出新文档,生成的数组列,数组列保存的数据是来自被处理的文档。
基本语法
{
$lookup:
{
from: ,
localField: ,
foreignField: ,
as:
}
}
其中,基本解释如下:from 同一个数据库下等待被join的集合。localField 源集合中的要被join 的值。foreignField 待join的集合的值as 为输出文档新增加的命名,
类比于以下的sql
SELECT *,
FROM collection
WHERE IN (SELECT *
FROM
WHERE = );
小案例
假设有如下的订单集合,保存的数据如下
db.orders.insert([
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
{ "_id" : 3 }
])
其中item对应的数据为商品名称。
另外一个就是商品库存集合,保存的数据如下
db.inventory.insert([
{ "_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 },
{ "_id" : 2, "sku" : "bread", description: "product 2", "instock" : 80 },
{ "_id" : 3, "sku" : "cashews", description: "product 3", "instock" : 60 },
{ "_id" : 4, "sku" : "pecans", description: "product 4", "instock" : 70 },
{ "_id" : 5, "sku": null, description: "Incomplete" },
{ "_id" : 6 }
])
此时sku等同于订单集合中的商品名称。在这种设计模式下,如果要查询订单表对应商品库存的情况,需要join两个集合。
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
使用look语句,实现join两个集合。此时返回的结果如下
{
"_id" : NumberInt("1"),
"item" : "almonds",
"price" : NumberInt("12"),
"quantity" : NumberInt("2"),
"inventory_docs" : [
{
"_id" : NumberInt("1"),
"sku" : "almonds",
"description" : "product 1",
"instock" : NumberInt("120")
}
]
}
{
"_id" : NumberInt("2"),
"item" : "pecans",
"price" : NumberInt("20"),
"quantity" : NumberInt("1"),
"inventory_docs" : [
{
"_id" : NumberInt("4"),
"sku" : "pecans",
"description" : "product 4",
"instock" : NumberInt("70")
}
]
}
{
"_id" : NumberInt("3"),
"inventory_docs" : [
{
"_id" : NumberInt("5"),
"sku" : null,
"description" : "Incomplete"
},
{
"_id" : NumberInt("6")
}
]
}
这样就完成了两个文档的join。
小实记
在以下的说明中,为描述方便,将 from对应的集合定义为 被join集合;待聚合的表成为源表;将 localField 和 foreignField 对应的Key 定义 比较列。
这个示例中,一共输出了三个文档,在没有再次聚合($match)的条件下,这个输出文档数量是以输入文档的数量来决定的(由order来决定),而不是以被Join的集合(inventory)文档数量决定。
在此需要特别强调的是输出的第三个文档。在源库中原文档没有要比较的列(即item值不存在,既不是Null值,也不是值为空),此时 和 被Join 集合比较,如果 被Join集合中 比较列 也恰好 为NUll 或 不存在的值,此时,判断相等 ,即会把 被Join集合中 比较列 为NUll 或 值不存在 文档 吸收进来。
小明菜市场
推荐阅读
●新知 | MongoDB 账号管理
●方案 | Mongodb 高可用落地方案
●介绍 | MyPerf4J 入门指南
●使用 | Java使用WebMagic 爬取网站
点击播放 GIF 0.0M