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?
CodePudding user response:
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).
CodePudding user response:
In this specfic scenario, you can follow these steps:
- create index on
{ username: 1 }
- create index on
{ kills: -1 }
- query with
find({ username: latest_user }
to get this user'skills
aslatest_user_kills
- query with
countDocuments({ kills: { $gt: latest_user_kills } })
to get the count of all users whose kills is higher than this latest_user - the resulting count from step 4 is the position of this individual player