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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With