With a MongoDB collection name department
with the following structure:
{
"_id":99,
"name":"Erick Kalewe",
"faculty":"Zazio",
"lecturers":[
{
"lecturerID":31,
"name":"Granny Kinton",
"email":"[email protected]",
"imparts":[
{
"groupID":70,
"codCourse":99
}
]
},
{
"lecturerID":36,
"name":"Michale Dahmel",
"email":"[email protected]",
"imparts":[
{
"groupID":100,
"codCourse":60
}
]
}
]
}
and another collection group
with this structure:
{
"_id":100,
"codCourse":11,
"language":"Romanian",
"max_students":196,
"students":[
{
"studentID":1
}
],
"classes":[
{
"date":datetime.datetime(2022, 5, 10, 4, 24, 19),
"cod_classroom":100
}
]
}
join them to get the following:
{
"_id":99,
"name":"Erick Kalewe",
"faculty":"Zazio",
"lecturers":[
{
"lecturerID":31,
"name":"Granny Kinton",
"email":"[email protected]",
"imparts":[
{
"groupID":70,
"codCourse":99
}
]
},
{
"lecturerID":36,
"name":"Michale Dahmel",
"email":"[email protected]",
"imparts":[
{
"_id":100,
"codCourse":11,
"language":"Romanian",
"max_students":196,
"students":[
{
"studentID":1
}
],
"classes":[
{
"date":datetime.datetime(2022, 5, 10, 4, 24, 19),
"cod_classroom":100
}
]
}
]
}
]
}
The objective is to get a report with the number of students taught by a professor from a department.
3
Answers
Query
(i think in general joining fields shouldn’t go deep inside)
(for rest argument i keep the $first)
we sum also the students based on the comment
(for rest arguments i keep the $first)
we take the lecture with the max students in the department
(mongodb can compare documents also)
Playmongo (you can put your mouse at the end of each stage to see
in/out
of that stage)You can try aggregation framework,
$lookup
withgroup
collection passlecturers.imparts.groupID
aslocalField
and pass_id
asforeignField
$addFields
to mergegroup
data withimports
and removegroup
fields because it is not needed$map
to iterate loop oflecturers
array$mergeObjects
to merge current object oflecturers
and updated object ofimports
$map
to iterate loop ofimports
array$mergeObjects
to merge current object ofimports
and found result fromgroup
$filter
to iterate loop ofgroup
array and find the group bygroupID
$arrayElemAt
to get first element from above filtered resultPlayground
Now that we understand the question (according to your other question), an answer can be:
department
document a set of all its relevant groups.$lookup
only the student ids for each group to create agroups
array.groups
data to eachlecturer
.maxImpartsStudents
which is the number of unique students perlecturer
from all of itsgroups
$reduce
thelecturers
array to include only thelecturer
with highestmaxImpartsStudents
.Which is much better than combining the solutions from both questions.
See how it works on the playground example