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

140
Views
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 answers
Answer question

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 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!