尝试使用$ lookup进行“JOIN”操作但结果计数正常但“as”文档为空
我有两个馆藏,我需要在 employer_jobscol
中 user_id 从 subscribercol 获取用户详细信息subscribercol
{
"_id" : ObjectId("58187e7551d244640626d7e1"),
"type" : "job_seeker",
"firstname" : "vishnu",
"lastname" : "kumar pv",
"email_array" : {
"primary" : "test@test.com",
"secondary" : "test@test.test",
"verified" : false
},
"address_array" : {
"address" : "test address22d",
"streetname" : "test222d",
"pincode" : "test222d",
"city" : "dddd",
"state" : "ALASKA2d",
"country" : "Argentinad"
},
"phone_array" : {
"primary" : "",
"secondary" : "",
"verified" : ""
},
"languages" : [
"english",
"malayalam",
"english2"
]
}
employer_jobscol
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test@test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : [
{
"user_id" : ObjectId("581b364751d2445c311cf6f1"),
"accepted" : false
},
{
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
}
]
}
我的数据库查询,(用 Robomongo 执行)
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "user_id",
foreignField: "_id",
as: "subscribercol_docs"
}
}
])
结果是
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test@test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : {
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
},
"subscribercol_docs" : []
}
这里 subscribercol_docs 是空数组我需要用户信息(姓名,地址等),
答案 0 :(得分:2)
由于本地文档中没有user_id字段,因此" applied_users.user_id" 试试这个
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "applied_users.user_id", // <-- check here
foreignField: "_id",
as: "subscribercol_docs"
}
}
])