Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying for a user relative leaderboard with MongoDB [duplicate]

Tags:

mongodb

I have a collection of users, each user has a points attribute (see schema below).

My end goal is to return a sorted array of limited documents according to a specific user location, or in other words, a small part of a leaderboard relative for a specific user location.

Currently I query and sort all users, find the user I want in the returned array and slice the array according to that. I was wondering if there is a query that will save me returning all users.

Sample User Schema:

/* 1 */
{
    "_id" : ObjectId("..."),
    "points" : 5852 ,
    "key" : "user1"
}

/* 2 */
{
    "_id" : ObjectId("..."),
    "points" : 3835,
    "key" : "user2"
}

/* 3 */
{
    "_id" : ObjectId("..."),
    "points" : 1984,
    "key" : "user3"
}

/* 4 */
{
    "_id" : ObjectId("...."),
    "points" : 2437,
    "key" : "user4"
}

Lets assume I want the query to return 3 documents sorted by points - The document of "user4" (my relative user), the document after him in the leaderboard ("user3" in the example above) and 1 document before him ("user2" in the above example)

Thanks!

Edit: Im using mongoose as well if this simplifies things.

Edit2: Please see below the expected output -

 /* 1 */
    {
        "_id" : ObjectId("..."),
        "points" : 3835,
        "key" : "user2"
    }
/* 2 */
    {
        "_id" : ObjectId("...."),
        "points" : 2437,
        "key" : "user4"
    }
 /* 3 */
    {
        "_id" : ObjectId("..."),
        "points" : 1984,
        "key" : "user3"
    }

Note that "user1" does not appear in the output as the query asks for 1 user ranked above and 1 user ranked below "user4"

like image 646
Aviram Gabay Avatar asked Oct 27 '25 10:10

Aviram Gabay


1 Answers

Sounds like you're trying to do this: rank leaderboard in mongo with surrounding players

As it says in the answer to that question, the easiest way to do it is with three queries. Even though that's an increase in the number of queries, the data you transfer will be significantly reduced.

like image 190
James Baker Avatar answered Oct 29 '25 23:10

James Baker