Created
June 27, 2016 21:28
-
-
Save undeadops/c0ebb66adc6e7872c0be4693bea88430 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 } } | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output will then look like this: