Home > Enterprise >  Mongoose Find Document Rank in Sorted Collection
Mongoose Find Document Rank in Sorted Collection

Time:04-03

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.

CodePudding user response:

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

  • Related