首页 > 解决方案 > 在返回的查询文档中添加排名系统?

问题描述

我的用户集合包含以下文档:

{"_id" : 1, point_count: "12"},
{"_id" : 2, point_count: "19"},
{"_id" : 3, point_count: "13"},
{"_id" : 4, point_count: "1233"},
{"_id" : 5, point_count: "1"},
... and about 1000 more

我的问题是:当我按 id 搜索时,是否可以根据 point_count 字段显示每个用户的排名?假设我使用此查询查找 id = 4 的用户

db.User.find({_id: 4})

假设我整个收藏中的最高 point_count 是 1233,我希望得到这个结果

{"_id" : 4, point_count: "1233", rank: 1}

排名 1 因为 1233 是最高 point_count

或者当我搜索 id = 5 的用户时,我的预期结果应该是

{"_id" : 5, point_count: "1", rank: 1000..something}

1000 ..something 因为它是最低级别的,并且文档中有大约 1000+ id。非常感谢大家在这里帮助我!

标签: mongodbmongoosemongodb-query

解决方案


推荐阅读