对数组进行排序并在 MongoDB 中添加排名字段 [英] Sort an array and add a rank field in MongoDB

查看:77
本文介绍了对数组进行排序并在 MongoDB 中添加排名字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 User 集合,它在 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

我的解决方案是:

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
}

想象一下,我们这里有非常大的数据.我可以使用 MongoDB 操作改进我的解决方案吗?

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

推荐答案

我认为你的方法很好,但只需将 results.length 更改为 user.length 但如果你想使用 mongoDB 操作这样做:

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
    }
  }
])

你可以使用lean()selectfind查询中的一些字段来提高性能

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

这篇关于对数组进行排序并在 MongoDB 中添加排名字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆