简体   繁体   中英

Mongodb How do I make this sorting of grabbing an individual players position function faster?


class User {
  constructor(doc) {
    this.username = doc.username;
    this.kills = doc.kills;
    this.deaths = doc.deaths;
  }
}

const res = await Calls.getAllUsers();

        const users = res.map((doc) => new User(doc));

        const sorted = users.sort((a, b) => b.kills - a.kills);

        const whereIam =
          sorted.indexOf(users.find((u) => u.username === latest_user)) + 1;

Hi, everyone I am trying to sort out a players position ( kills)

They would do /stats and they would get a position based on the highest kills This takes more than five minutes to determind a players position with 26,000 documents and 2,000 documents being made everyday, what are the steps to make this faster or to change?

You look to be getting all users and then doing the sort and search in memory. As your data set gets larger that will get much more memory intensive.

So first suggestion would be to get Mongo to be doing that for you in your query.

Adding to that, since Mongo will be doing the query, you'll want indexes in Mongo on the username and kills fields.

If there's a reason you want all the users in memory though, then you could consider a hash table to help with your user lookups, but there's no way around sorting time. Make sure your sort is using a reasonable algorithm (that's a whole subject on it's own, but Quicksort is the one that has the best average performance).

In this specfic scenario, you can follow these steps:

  1. create index on { username: 1 }
  2. create index on { kills: -1 }
  3. query with find({ username: latest_user } to get this user's kills as latest_user_kills
  4. query with countDocuments({ kills: { $gt: latest_user_kills } }) to get the count of all users whose kills is higher than this latest_user
  5. the resulting count from step 4 is the position of this individual player

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM