Home > Mobile >  Order users by score in Firebase realtime database
Order users by score in Firebase realtime database

Time:04-19

I am trying to order users by their highest scores to create a leaderboard, however, when trying to order them by the score, what I am getting is the users ordered in an alphabetical order.

Here is an image of the database structure: database

This is my attempt at getting the ordered list of users:

List<User> list = new List<User>();
list = (await firebase.Child("Users").OrderBy("HighScore").LimitToLast(10).OnceAsync<User>()).Select(item => new User
    {
        Username = item.Object.Username,
        Password = item.Object.Password,
        HighScore = item.Object.HighScore
    }).ToList();

Here is the result of the query ref/Users/.json?orderBy="HighScore"&limitToLast=10:
{"a":{"HighScore":500,"Password":"a","Username":"a"},"ac":{"HighScore":0,"Password":"ac","Username":"ac"},"b":{"HighScore":1100,"Password":"b","Username":"b"}}

And here are the database rules: rules

What am I doing wrong?

CodePudding user response:

You should use orderByChild("HighScore") instead of orderBy("HighScore")

Check the documentation for more information https://firebase.google.com/docs/database/web/lists-of-data#sort_data

CodePudding user response:

Turns out that my query does return the 10 users with the highest score. But for some reason the list my code gives is ordered alphabetically based on the username and not based on the score field. So what I did was sorting the list after I got the list of the 10 best users List<User> orderedList = list.OrderByDescending(o => o.HighScore).ToList();

Now it seems to work the way I intended it.

  • Related