Search code examples
pythondatabasemongodbpymongo

How to select N max values in a mongodb database in PyMongo


I am trying to select a number of the biggest elements in a mongodb collection. For example, my database collection is structured as:

username score
person_a 500
person_b 600

I already know how to select the person with the max score value (written below):

max = leaderboard_data.find_one(sort=[("score", -1)])["score"]

But how would I edit this to select n biggest items in the mongodb database collection based off of the "score" field? Like the top 10 scores for example?

I've seen the solution using the $limit notation when I was looking at the mongodb specific docs but I have no idea how to use it in PyMongo.


Solution

  • use a find() statement in combination with sort and limit.

    import pymongo
    
    db = pymongo.MongoClient()['test']
    
    # Set up some data
    for i in range(20):
        db['mycollection'].insert_one({'username': f'person{i}', 'score': i})
    
    # sort by score descending, limit to top 10
    for record in db['mycollection'].find({}, {'_id': 0}).sort('score', pymongo.DESCENDING).limit(10):
        print(record)
    

    prints:

    {'username': 'person19', 'score': 19}
    {'username': 'person18', 'score': 18}
    {'username': 'person17', 'score': 17}
    {'username': 'person16', 'score': 16}
    {'username': 'person15', 'score': 15}
    {'username': 'person14', 'score': 14}
    {'username': 'person13', 'score': 13}
    {'username': 'person12', 'score': 12}
    {'username': 'person11', 'score': 11}
    {'username': 'person10', 'score': 10}