MongoDB是一种文档型数据库,它支持关联查询(Join),但由于MongoDB的文档结构不同于关系型数据库,它的关联查询方法也不同。本文将介绍MongoDB实现关联查询(Join)的几种方法。
内连接
内连接(Inner Join)是最常用的关联查询方法,只返回两个集合之间有关联的文档,即只返回两个集合中都存在的文档,MongoDB实现内连接的方法主要有两种:
- 第一种方法是使用MongoDB的$lookup聚合操作符,它允许在一个集合中查找另一个集合,返回两个集合之间有关联的文档,示例如下:
db.orders.aggregate([
{
$lookup:
{
from: "products",
localField: "product_id",
foreignField: "_id",
as: "order_details"
}
}
])
- 第二种方法是使用MongoDB的$match和$lookup聚合操作符,它允许在一个集合中查找另一个集合,同时可以指定查找条件,返回两个集合之间有关联的文档,示例如下:
db.orders.aggregate([
{
$match: {
status: "shipped"
}
},
{
$lookup:
{
from: "products",
localField: "product_id",
foreignField: "_id",
as: "order_details"
}
}
])
左外连接
左外连接(Left Outer Join)是查询两个集合之间的关联,但返回左集合中的所有文档,即使右集合中没有相关联的文档,MongoDB实现左外连接的方法主要有两种:
- 第一种方法是使用MongoDB的$lookup聚合操作符,它允许在一个集合中查找另一个集合,同时可以指定返回左集合中的所有文档,示例如下:
db.orders.aggregate([
{
$lookup:
{
from: "products",
localField: "product_id",
foreignField: "_id",
as: "order_details"
}
},
{
$addFields: {
order_details: { $ifNull: ["$order_details", []] }
}
}
])
- 第二种方法是使用MongoDB的$match和$lookup聚合操作符,它允许在一个集合中查找另一个集合,同时可以指定查找条件和返回左集合中的所有文档,示例如下:
db.orders.aggregate([
{
$match: {
status: "shipped"
}
},
{
$lookup:
{
from: "products",
localField: "product_id",
foreignField: "_id",
as: "order_details"
}
},
{
$addFields: {
order_details: { $ifNull: ["$order_details", []] }
}
}
])
右外连接
右外连接(Right Outer Join)是查询两个集合之间的关联,但返回右集合中的所有文档,即使左集合中没有相关联的文档,MongoDB实现右外连接的方法主要有两种:
- 第一种方法是使用MongoDB的$lookup聚合操作符,它允许在一个集合中查找另一个集合,同时可以指定返回右集合中的所有文档,示例如下:
db.products.aggregate([
{
$lookup:
{
from: "orders",
localField: "_id",
foreignField: "product_id",
as: "order_details"
}
},
{
$addFields: {
order_details: { $ifNull: ["$order_details", []] }
}
}
])
- 第二种方法是使用MongoDB的$match和$lookup聚合操作符,它允许在一个集合中查找另一个集合,同时可以指定查找条件和返回右集合中的所有文档,示例如下