rank leaderboard in mongo with surrounding players

后端 未结 1 1840
名媛妹妹
名媛妹妹 2020-12-06 03:37

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

相关标签:
1条回答
  • 2020-12-06 04:13

    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.

    0 讨论(0)
提交回复
热议问题