与周围的玩家在mongo中排名排行榜 [英] rank leaderboard in mongo with surrounding players

查看:57
本文介绍了与周围的玩家在mongo中排名排行榜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何创建查询以获取当前玩家的排名和周围玩家的排名.例如,如果我有一个排行榜集合,其中包含名称和分数

how would I create a query to get both the current player's rank and the surrounding player ranks. For example, if I had a leaderboard collection with name and points

{name: 'John', pts: 123}

如果John在第23位,我也想在第22位和第24位显示用户名.

If John was in 23rd place, I would want to show the names of users in the 22nd and 24th place as well.

我可以查询pts大于123的排行榜项目数来获得John的排名,但是如何有效地获得排名在当前玩家之上和之下的一名玩家呢?我可以仅根据索引位置获得商品吗?

I could query for a count of leader board items with pts greater than 123 to get John's rank, but how can I efficiently get the one player that is ranked just above and below the current player? Can I get items based on index position alone?

我想我可以进行2次查询,首先是获取用户排名的数字,然后是跳过限制查询,但这似乎效率不高,而且似乎没有有效地使用索引

I suppose I can make 2 queries, first to get the number the rank position of a user, then a skip limit query, but that seems inefficient and doesn't seem to have an efficient use of the index

db.leaderboards.find({pts:{$gt:123}}).count();
-> 23

db.leaderboards.find().skip(21).limit(3)

最后一个查询似乎使用其索引扫描了24条记录,有没有办法我可以合理地使用范围查询或更有效的方法呢?如果用户排名很低(例如第50,000位),我会看到这成为一个问题.

The last query seems to scan across 24 records using the its index, is there a way I can reasonably do this with a range query or something more efficient? I can see this becoming an issue if the user is very low ranked, like 50,000th place.

推荐答案

您将需要执行三个查询:

You'll need to do three queries:

var john = db.players.findOne({name: 'John'})
var next_player = db.players.find(
    {_id: {$ne: john._id}, pts: {$gte: john.pts}}).sort({pts:1,name:1}).limit(-1)[0]
var previous_player = db.players.find(
    {_id: {$ne: john._id}, pts: {$lte: john.pts}}).sort({pts:-1,name:-1}).limit(-1)[0]

在名称和分数上创建索引.

Create indexes on name and pts.

这篇关于与周围的玩家在mongo中排名排行榜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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