Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Mongoose Find Document Rank in Sorted Collection

I'm creating an award system for my users and i want to show them their ranks among the other users. I tried to achieve this by some built-in JS functions but i couldn't do it.

Level Schema

{
  userID: String,
  xp: Number,
  lastUpdate: Number
}

I'm sorting this collection by "descending" XP:

await schemas.levels.find({}).sort({
    xp: -1
})

How can i get a users rank (by userID) in this sorting array.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Hello if you want to find the position of the document (rank of the user in an array) irrespective of any order, it is currently not possible as MongoDb does not store the documents in a specific order. However, there is a way around this by modifying the data returned from mongo.

var docIndex = 0;
db.schemas.find({}, {
  "_id": 1
}).sort({
  "xp": -1
}).forEach(function(doc) {
  docIndex++;
  if (userID == doc["userID"]) {
    print("User's Rank is..." + docIndex);
    // Add rank to doc payload here //
    return false;
  }
});

You could also check this post Get Position of Document in the answer section it has lost of ways to return document position

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!