0

I'm storing scoreboard along with date in milliseconds and query the date using startAt and endAt methods. And this is giving me all the users in that date range, now I want to sort the users based on score but I'm not able to do that.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
DHANANJAY KUMAR
  • 86
  • 1
  • 13
  • Show your work first. And why don't you sort it after you received in client? – Harry T. Oct 12 '18 at 02:49
  • In firebase realtime database while fetching we cannot group by and sort in single query as in sql.. If you want to sort the scores on a single day, you want to combine that date and score field to a single field in db each nodes – Jinson Paul Oct 12 '18 at 03:37
  • Hey @DHANANJAYKUMAR do mark the answer as correct by clicking the V type tick mark looking button next to it, this helps future readers of this question and I'd appreciate that too. Cheers! :) – PradyumanDixit Nov 24 '18 at 14:09

2 Answers2

0

This is a very common problem. As you've not attached you database, or your code, I can't give you the proper code of how to do this, but the best way to retrieve your users in the same order of their score can be done by a basic principle.

The basic principle is that in addition to setting the name and score in a user object, you can use setWithPriority to also set a priority for it.

Priority in this particular case can be the user's score (if its numeric, it will automatically be sorted for you). You can then use the .limit(10) query to get the list of top 10 users.

You'll also have to implement the child_added, child_changed and child_removed events to handle the cases of a new user entering the top 10, someone changing position and someone leaving the top 10 list respectively.

You can read and know more about this here: https://www.firebase.com/tutorial/#example/leaderboard

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
0

Unfortunately, you cannot achieve this with Firebase realtime database without making some changes in the structure of your database. Unlike in Cloud Firestore, the realtime database doesn't have the capability to perform filtering on multiple properties (using "multiple WHERE clauses" as can be said in SQL terms).

If you want to check for matches on multiple properties, you'll have to create a composite property that can contain a combination of the properties that you are looking for. As an example, you'll need a string value that has the score and the date together like explained in my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193