Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save undeadops/c0ebb66adc6e7872c0be4693bea88430 to your computer and use it in GitHub Desktop.
Save undeadops/c0ebb66adc6e7872c0be4693bea88430 to your computer and use it in GitHub Desktop.
# Calculate Highest Class Average from student Average (exclude quizes)
### Data ###
> db.grades.findOne()
{
"_id" : ObjectId("50b59cd75bed76f46522c351"),
"student_id" : 0,
"class_id" : 16,
"scores" : [
{
"type" : "exam",
"score" : 59.1805667559299
},
{
"type" : "quiz",
"score" : 47.58960202938239
},
{
"type" : "homework",
"score" : 6.48470951607214
},
{
"type" : "homework",
"score" : 68.33519637418685
},
{
"type" : "homework",
"score" : 78.53068038180965
}
]
}
###
## Solution
db.grades.aggregate( [
{ $match:
{ $or: [ {"scores.type":"homework"},
{"scores.type":"exam"}
]
}
},
{ $unwind : "$scores" },
{
$group:{ "_id": "$class_id",
"score": { $avg: "$scores.score"}
}
},
{$project:
{
_id: 0,
class_id: "$_id",
class_avg: { $sum:"$score"}
}
},
{$sort : { class_avg: -1 } }
])
@undeadops
Copy link
Author

Output will then look like this:

>
> db.grades.aggregate( [
...     { $match:
...       { $or: [ {"scores.type":"homework"},
...                {"scores.type":"exam"}
...             ]
...       }
...     },
...     { $unwind : "$scores" },
...     {
...       $group:{ "_id": "$class_id",
...                "score": { $avg: "$scores.score"}
...               }
...     },
...     {$project:
...       {
...         _id: 0,
...         class_id: "$_id",
...         class_avg: { $sum:"$score"}
...       }
...     },
...     {$sort : { class_avg: -1 } }
... ])
{ "class_id" : 1, "class_avg" : 58.3972086085214 }
{ "class_id" : 26, "class_avg" : 58.14625609715404 }
{ "class_id" : 9, "class_avg" : 55.95997522714545 }
{ "class_id" : 11, "class_avg" : 55.02367012378275 }
{ "class_id" : 16, "class_avg" : 54.635642229166656 }
{ "class_id" : 5, "class_avg" : 54.164419161512036 }
{ "class_id" : 4, "class_avg" : 53.10783283118922 }
{ "class_id" : 10, "class_avg" : 53.056620203523586 }
{ "class_id" : 20, "class_avg" : 52.640394943783384 }
{ "class_id" : 13, "class_avg" : 51.76529805087406 }
{ "class_id" : 7, "class_avg" : 50.81480967725756 }
{ "class_id" : 29, "class_avg" : 50.23323724268069 }
{ "class_id" : 14, "class_avg" : 50.170689358225644 }
{ "class_id" : 23, "class_avg" : 50.1215954808574 }
{ "class_id" : 19, "class_avg" : 50.00452526153963 }
{ "class_id" : 24, "class_avg" : 49.72083585510094 }
{ "class_id" : 0, "class_avg" : 49.55606780344127 }
{ "class_id" : 21, "class_avg" : 48.928724328732955 }
{ "class_id" : 3, "class_avg" : 48.874180390351746 }
{ "class_id" : 27, "class_avg" : 47.61594896756118 }
Type "it" for more
>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment