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