mongodb 加入多个集合
mongodb join multiple collections
我想 "join" 使用 mongochef 在 MongoDB 中创建 3 个集合。这些集合是 "Order"、"Employee" 和 "City"。我尝试使用临时集合,但效果不佳。
现在我在第一个 "join".
中使用 var = a
如果我想显示"a",只显示20个结果。
您有想法或其他解决方案吗?
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 是 不是 关系数据库...
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"
}
}
]);
我想 "join" 使用 mongochef 在 MongoDB 中创建 3 个集合。这些集合是 "Order"、"Employee" 和 "City"。我尝试使用临时集合,但效果不佳。 现在我在第一个 "join".
中使用 var = a如果我想显示"a",只显示20个结果。 您有想法或其他解决方案吗?
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 是 不是 关系数据库...
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"
}
}
]);