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

142
Visualizações
Sort an array and add a rank field in MongoDB

Let's say I have a User collection which stores each user's score and name in MongoDB.

when listing all users, I want to add a new field to it to give me the ranking of the user with respect to score

My solution is :

async findRank() {
  const users = await User.find().sort({score: -1})
  let ObjectOfResults = JSON.parse(JSON.stringify(users))
  for (let index = 0; index < ObjectOfResults.length; index++) {
    ObjectOfResults[index].rank = index
  }
  return ObjectOfResults
}

So imagine we have very big data in here. Can I improve my solution using MongoDB operations?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I think your method is good but just change the results.length to user.length but if you want using mongoDB operation do like this:

db.collection.aggregate([
  {
    "$sort": {
      "score": -1
    }
  },
  {
    "$group": {
      "_id": "",
      "items": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$unwind": {
      "path": "$items",
      "includeArrayIndex": "items.rank"
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$items"
    }
  },
  {
    "$sort": {
      "score": -1
    }
  }
])

you can use lean() and select the some fields in find query to increase performance

async findRank() {
  const users = await User.find({},"_id score").sort({score: -1}).lean()
  for (let index = 0; index < users.length; index++) {
    users[index].rank = index
  }
  return users
}
if you want group by the documents based on name or score ... it's better use mongodb operation
over 4 years ago · Santiago Trujillo 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