在MongoDB中,聚合管道查询可以通过$lookup操作符来实现连接(join)操作。$lookup允许你将来自另一个集合的文档与当前集合的文档进行连接。以下是一个简单的示例:
假设我们有两个集合:orders和customers。orders集合包含订单信息,customers集合包含客户信息。我们想要查询每个订单及其对应的客户信息。
orders集合:
{
"_id": 1,
"customer_id": 1,
"product": "Laptop",
"price": 1000
}
customers集合:
{
"_id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
我们可以使用以下聚合管道查询来连接这两个集合:
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customer_id",
foreignField: "_id",
as: "customer_info"
}
},
{
$unwind: "$customer_info"
},
{
$project: {
_id: 1,
customer_id: 1,
product: 1,
price: 1,
customer_name: "$customer_info.name",
customer_email: "$customer_info.email"
}
}
])
这个查询的工作原理如下:
$lookup操作符从customers集合中查找与orders集合中的customer_id相匹配的文档,并将结果存储在名为customer_info的新数组字段中。$unwind操作符将customer_info数组拆分为多个文档,每个文档包含一个客户信息。$project操作符重新构造输出文档,将客户名称和电子邮件字段分别重命名为customer_name和customer_email。查询结果:
{
"_id": 1,
"customer_id": 1,
"product": "Laptop",
"price": 1000,
"customer_name": "John Doe",
"customer_email": "john.doe@example.com"
}