Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda