这是对my previous question的后续任务。
我有以下mongoDB文档结构
School1
Division1
Classroom1
Student1 last name
Student2 last name
Classroom2
< empty classroom >
Student3 last name
Student4 last name
Divison2
Classroom1
-
Classroom2
-
School2
-
-
-
-
-
我需要的是以下形式的结果:
{
school: school1,
division: division1,
classroom: classroom1,
student: student1,
},
...
{
school: school1,
division: division1,
student: student3,
}
现在我正在做
db.collection.aggregate(
[
{$unwind:"$schools"},
{$unwind:"$school.divisions"},
{$unwind:"$school.divisions.classrooms"},
{
$project: {
school: "$schools._id",
division: "$school.divisions._id",
classroom: "$school.divisions.classrooms._id",
student: "$school.divisions.classrooms.students._id"
}
},
{$unwind:"$student"}
]
)
但是我没有得到所需的东西,因为不是所有的学生都在教室里,而是直接在一个部门里。无论嵌套级别如何,我都需要查询来获取学生。
什么是一个好的方法?
编辑1 :收藏集如下所示:
{
"_id" : "school1",
"divisions": [
{
"_id": "division1",
"classrooms" : [
"_id": "classroom1",
"students" : [
{
student1
},
{
student2
}
]
]
"students" : [],
},
{
"_id": "division2",
"classrooms:" [],
"students": [
{
student3
},
{
student4
}
]
}
]
}
}