Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda