Having the sample data below, I'm trying to get a total count of students and the combined topScore of each subject of each section and floor:
[{
"section": "east",
"floor": "1st",
"classrom": 100,
"tests": [
{
"subject": "math",
"students": 30,
"topScore": 90
},
{
"subject": "english",
"students": 40,
"topScore": 80
}]
},
{
"section": "east",
"floor": "1st",
"classrom": 150,
"tests": [
{
"subject": "math",
"students": 35,
"topScore": 85
},
{
"subject": "english",
"students": 45,
"topScore": 70
}]
}]
Desired result:
[{
"section": "east",
"floor": "1st",
"classroms": [100, 150],
"tests": [
{
"subject": "math",
"totalStudents": 65,
"combinedTopScores": 175
},
{
"subject": "english",
"totalStudents": 85,
"combinedTopScores": 150
}]
}]
What I have so far is:
db.collection.aggregate([{
"$group": {
"_id": {
"section": "$section",
"floor": "$floor"
},
"classrooms": { "$push": "$classroom" },
"tests": { "$push": "$tests" }
}
}])
Which gives me:
{
"_id":
{
"section": "east",
"floor": "1st"
},
"classrooms": [100, 150],
"tests": [
[{
"subject": "math",
"students": 30,
"topScore": 90
},
{
"subject": "english",
"students": 40,
"topScore": 80
}],
[{
"subject": "math",
"students": 35,
"topScore": 85
},
{
"subject": "english",
"students": 45,
"topScore": 70
}]
]
}
So I'm having a hard time figuring out the $sum of the tests array. Specially because it has to be grouped by subject.
Can anybody point me a direction? Is that even possible?
Thanks!