Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda