更新时间:2023-02-18 12:34:20
如果您希望将每个输出作为一个用户,则不要打扰分组,您只需做两倍的工作即可.
Don't bother grouping if you want the the each output to be one user, you're just doing double the work.
将查询更改为此:
{
"$match" : {
"clgID" : {
"$in" : [
"100",
"200"
]
}
}
},
{
"$lookup" : {
"from" : "Subjects",
"localField" : "clgID",
"foreignField" : "college.collegeID",
"as" : "clg"
}
},
{
"$unwind" : {
"path" : "$clg",
"preserveNullAndEmptyArrays" : true
}
},
{
"$unwind" : {
"path" : "$clg.members.student",
"preserveNullAndEmptyArrays" : true
}
},
{
"$project" : {
"collegeName" : "$name",
"student" : "$clg.members.student"
}
}
],
第二步展开时,每个对象都包含大学名称和-ONE-学生,因此我们现在要做的就是以所需的形式进行项目设计.
Now with the second unwind each object contains the college name and -ONE- student so all we need to do now is project in the required form.
根据要求进行完整查询
{
"$match" : {
"clgID" : {
"$in" : [
"100",
"200"
]
}
}
},
{
"$lookup" : {
"from" : "Subjects",
"localField" : "clgID",
"foreignField" : "college.collegeID",
"as" : "clg"
}
},
{
"$unwind" : {
"path" : "$clg",
"preserveNullAndEmptyArrays" : true
}
},
{
"$unwind" : {
"path" : "$clg.members.student",
"preserveNullAndEmptyArrays" : true
}
},
{
"$lookup" : {
"from" : "CollegeProducts",
"localField" : "clg.members.student",
"foreignField" : "StudentProdcutID",
"as" : "clgproduct"
}
},
{ // can skip this unwind if theres always only one match.
"$unwind" : {
"path" : "$clgproduct",
"preserveNullAndEmptyArrays" : true
}
},
{
"$match" : {
"clgproduct.CID" : "Facebook"
}
},
{
"$lookup" : {
"from" : "UserDetails",
"localField" : "clgproduct.StudentID",
"foreignField" : "StudentID",
"as" : "student"
}
},
{ // can skip this unwind if theres always only one user matched.
"$unwind" : {
"path" : "$student",
"preserveNullAndEmptyArrays" : true
}
},
{
"$project" : {
"collegeName" : "$name",
"student" : "$student.name"
}
}
],