使用$lookup
与$mergeObjects
配合使用以及进行指定多个连接条件
注意!!
$lookup是如果涉及关联"_id",注意两个字段的类型,用string类型匹配ObjectId类型是关联不上的
准备数据
//订单表
db.orders.insert([
{
"_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 },
{
"_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 },
{
"_id" : 3 }
])
//库存表
db.inventory.insert([
{
"_id" : 1, "sku" : "almonds", description: "product 1", "instock" : 120 }, "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 }
])
两种用法
1.一种关联
{
$lookup:
{
//要关联的从表名
from: <collection to join>,
//主表关联字段
localField: <field from the input documents>,
//从表中与主表关联的字段
foreignField: <field from the documents of the "from" collection>,
//别名
as: <output array field>
}
}
2.自定义多种关联
{
$lookup:
{
//要关联的从表名
from: <collection to join>,
//自定义变量有一个或多个变量
let: {
<var_1>: <expression>, …, <var_n>: <expression> },
//自定义的操作从表的聚合但不允许使用out和merge操作
pipeline: [ <pipeline to execute on the collection to join> ],
//别名
as: <output array field>
}
}
orders表为主表 inventory表为从表 根据 orders表的item字段与inventory表的sku进行关联
db.orders.aggregate([
{
$lookup:
{
from: "inventory",
localField: "item",
foreignField: "sku",
as: "inventory_docs"
}
}
])
该操作返回以下文档:
// 1
{
"_id": 1,
"item": "almonds",
"price": 12,
"quantity": 2,
"inventory_docs": [
{
"_id": 1,
"sku": "almonds",
"description": "product 1",
"instock": 120
}
]
}
// 2
{
"_id": 2,
"item": "pecans",
"price": 20,
"quantity": 1,
"inventory_docs": [
{
"_id": 4,
"sku": "pecans",
"description": "product 4",
"instock": 70
}
]
}
// 3
{
"_id": 3,