Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

235
Vistas
Pymongo: Limiting the results used to calculate the average in a pipeline

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'])
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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}
}])
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda