Creating a constantly changing leaderboard

async def boards(ctx, map_code, level, title, query):
    """Display boards for scoreboard and leaderboard commands."""
    rank_number = 1
    async for entry in WorldRecords.find(query).sort("record", 1).limit(10):
        # Do stuff for first record entry . .
        rank_number += 1

I have this code to display the top 10 time records of a race.
How can I change the rank # to be a part of the document, rather than an iteration count in a loop?
I would like to add a field for rank and have that automatically update the others for that particular race.

If there were 3 records:

  1. 3.23
  2. 6.35
  3. 10.00

and a new one comes in say 5.12,
it would insert it between 6.35 and 3.23 giving it rank 2 and moving the others below it to 3 and 4, and so on.

  1. 3.23
  2. 3.23
  3. 6.35
  4. 10.00

Would triggers be a good solution to this? or would there be some way to do it in Python?

If you included rank as part of the document every insert would require you to update the rank field to reposition every document. This means a single write fans out to N writes. Database writes are slow so this is a bad idea.

On the other hand for a well tuned database database reads (especially with repeated reads of the same data) will be very fast so the solution you have outlined will work perfectly. If you add an index on the time field the read will be near instantaneous.

You could also add a project field to only return the time record as opposed to other elements of the document. This reduces the amount of data returned.

So you’re saying triggers would be a good solution? Could you point me in the right direction on them? I’ve looked at the docs but I didn’t see anything too helpful for this problem. Maybe I didn’t look hard enough.

I’m not sure of the question you are asking. Do you want to only react when a new measurement comes in? In that case you would need to use a Change Stream to watch the collection for new entries. My colleague @Naomi_Pentrel has written an excellent post on the subject.

Hi @nebula, Have you found anything in this case? as I am also working on something similar to this model.

Please let me know if you have any solution to this.

Thanks in advance.