由于我是MongoDB的新蜜蜂,因此难以在集合中执行联接。我需要加入特定ID的两个集合。实际上我正在使用模型来实现数据库目的。
Collection 1
{
"id" : "1",
"user_id" : "101",
"job_id" : "j1001"
}
{
"id" : "2",
"user_id" : "101",
"job_id" : "j1002"
}
{
"id" : "3",
"user_id" : "101",
"job_id" : "j1003"
}
收集2
{
"id" : "1",
"job_id" : "j1001",
"name" : "Software engineer",
}
{
"id" : "2",
"job_id" : "j1002",
"name" : "Project manager"
}
{
"id" : "3",
"job_id" : "j1003",
"name" : "FullStack Developer"
}
我想检索collection1中user_id为{1}}的collection1中的所有名称
预期结果将是这样的
101
非常感谢任何帮助。在此先感谢!
答案 0 :(得分:0)
您可以将$lookup阶段与MongoDB的aggregate框架一起使用。
的语法
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
实施例
db.collection1.aggregate([
{
$lookup:
{
from: "collection2",
localField: "id1",
foreignField: "reference id which will be same as id1",
as: "Array_Docs"
}
}
])