I'm using pymongo and trying to create a simple list of averages where my collection simply has a load of names and times. (its a simple maths game where your speed for answering questions correctly is stored).
Each result is added to the the DB through the python-eve REST api:
{
"_id" : ObjectId("5866ed13fdc3f36f0620dfdb"),
"_updated" : ISODate("2016-12-30T23:26:11Z"),
"score" : 1,
"name" : "adrian",
"time" : 2.7628954648971558,
"level" : "1",
"_etag" : "08dcbbf3718f837194ba6b439cfb6b3de1d5994f",
"_created" : ISODate("2016-12-30T23:26:11Z")
}
So I have both created and updated times.
I want to show the average time taken for each players most recent 10 scores. Currently I have a working group being created for the average of ALL scores, but I need the 10 most recent. Can I apply a limit to the $avg expression or is there some better way? Thanks for any help.
db = client.mathsgame4
pipe = [{'$group':
{'_id': '$name',
'average': {'$avg': '$time'},
}
},
{'$sort': {'average': 1}}]
res = db.results.aggregate(pipeline=pipe)
for each in res:
print(each['_id'] + " average is " + "%.2f" % each['average'])
One more option you can try something like this. You can combine $avg and $slice in the $project stage.
aggregate([{
'$sort': {'name': 1,'_created': -1}
}, {
'$group': {
'_id': '$name',
'times': {'$push': '$time'},
}
}, {
'$project': {
'average': {'$avg': {'$slice': ['$times', 10]}
}
}
}, {
'$sort': {'average': 1}
}])