以下の集計クエリを試すことができます。
以下のクエリはsections
をプッシュします department
に それらが結合されたときと$group
部門をプッシュして最終的な構造を作成します。
db.college.aggregate([
{
"$match": {
"university_id": "5834ecf7432d92675bde9d82"
}
},
{
"$lookup": {
"localField": "_id",
"from": "departments",
"foreignField": "college_id",
"as": "departments"
}
},
{
"$unwind": {
"path": "$departments",
"preserveNullAndEmptyArrays": true
}
},
{
"$lookup": {
"localField": "departments._id",
"from": "sections",
"foreignField": "department_id",
"as": "departments.sections"
}
},
{
"$group": {
"_id": "$_id",
"name": {
"$first": "$name"
},
"university_id": {
"$first": "$university_id"
},
"departments": {
"$push": "$departments"
}
}
}
])