mongodb 加入多个集合 [英] mongodb join multiple collections
问题描述
我想使用 mongochef 在 MongoDB 中加入"3 个集合.集合是订单"、员工"和城市".我尝试使用临时集合,但它无效.现在我使用 var = a 作为第一个加入".
I'd like to "join" 3 Collections in MongoDB by using mongochef. The collections are "Order", "Employee" and "City". I tried to use temp collections, but it is not effective. Now I am using var = a for the first "join".
如果我想显示a",则只显示 20 个结果.您有什么想法或其他解决方案吗?
If I 'd like to show "a", there are displayed 20 results only. Do you have an idea or another solution?
var a = db.Order.aggregate([
{
$lookup:
{
from: "City",
localField: "City Key",
foreignField: "City Key",
as: "lsg"
}
},
{
$unwind: "$lsg"
},
{
$project:
{
"_id":1,
"Salesperson Key":1,
"City": "$lsg.City"
}
}
])
a;
var b = db.Employee.aggregate([
{
$lookup:
{
from: "a",
localField: "Employee Key",
foreignField: "Salesperson Key",
as: "lsg2"
}
},
{
$unwind: "$lsg2"
},
{
$project:
{
"_id":1,
"Employee":1
}
}
])
预先感谢您的回复.
推荐答案
您可以放置多个 $lookup 阶段,因此您可以使用这样的查询(无法测试但应该可以工作)但是您应该避免多个连接,请记住 MongoDB 不是关系数据库...
you can put multiple $lookup stages, so you could use a query like this (could't test it but should work) But you should avoid multiple joins, keep in mind that MongoDB is not a relational database...
db.Order.aggregate([
{
$lookup:{
from:"City",
localField:"City Key",
foreignField:"City Key",
as:"lsg"
}
},
{
$unwind:"$lsg"
},
{
$lookup:{
from:"Employee",
localField:"Salesperson Key",
foreignField:"Employee Key",
as:"lsg2"
}
},
{
$unwind:"$lsg2"
},
{
$project:{
"_id":1,
"Employee":1,
"Salesperson Key":1,
"City":"$lsg.City"
}
}
]);
这篇关于mongodb 加入多个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!