Skip to content

Instantly share code, notes, and snippets.

@Michael-J-Ward
Last active February 6, 2016 19:13
Show Gist options
  • Save Michael-J-Ward/97774be4510cbec3901e to your computer and use it in GitHub Desktop.
Save Michael-J-Ward/97774be4510cbec3901e to your computer and use it in GitHub Desktop.
mongoDB aggregation example
> db.students.find().limit(2).pretty()
{
"_id" : 2,
"name" : "Corliss Zuk",
"scores" : [
{
"score" : 67.03077096065002,
"type" : "exam"
},
{
"score" : 6.301851677835235,
"type" : "quiz"
},
{
"score" : 20.18160621941858,
"type" : "homework"
}
]
}
{
"_id" : 3,
"name" : "Bao Ziglar",
"scores" : [
{
"score" : 71.64343899778332,
"type" : "exam"
},
{
"score" : 24.80221293650313,
"type" : "quiz"
},
{
"score" : 1.694720653897219,
"type" : "homework"
}
]
}
> db.students.aggregate([
... {$match:
... {'name': {$in: ['Corliss Zuk', 'Bao Ziglar']}}
... },
... {$project:
... {'_id': 0,
... 'name': 1,
... 'total_score': {$sum: '$scores.score'},
... 'avg_score': {$avg: '$scores.score'},
... 'max_score': {$max: '$scores.score'},
... 'min_score': {$min: '$scores.score'},
... 'count': {$size: '$scores.score'}
... }
... },
... ])
{ "name" : "Corliss Zuk", "total_score" : 93.51422885790383, "avg_score" : 31.171409619301276, "max_score" : 67.03077096065002, "min_score" : 6.301851677835235, "count" : 3 }
{ "name" : "Bao Ziglar", "total_score" : 98.14037258818367, "avg_score" : 32.71345752939455, "max_score" : 71.64343899778332, "min_score" : 1.694720653897219, "count" : 3 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment