25

There is this list of Books in the Firebase Realtime Database:

[
  {
    title: "Don't Make Me Think",
    upvotes: 110
  },
  {
    title: "The Mythical Man Month",
    upvotes: 111
  },
  {
    title: "Code Complete 2",
    upvotes: 112
  }
]

By default, the query below returns this list in ASC order:

firebase.database().ref('books').orderByChild('upvotes')

How can I query and order them by upvotes DESC instead?

hyang123
  • 1,208
  • 1
  • 13
  • 32
  • 1
    If I am correct, the proposed solution in the above link suggests that I store the `upvote` property as a negative number. Then, when rendering, it should be transformed into a positive integer again. If so, it seems kind of hacky since the data in my database does not truly reflect the upvote of the books. – hyang123 Jul 27 '17 at 18:31
  • 3
    I understand that concern. However, it's a number - whether it's positive or negative you know what it represents. Optionally, you can store the negative version of the number in another child node which you can use for sorting. You could always sort in code as well. – Jay Jul 27 '17 at 20:01
  • 1
    Use Collections.reverse(thearray); on the results – Daniel Nyamasyo Apr 07 '20 at 05:26
  • once you get a response from firebase, you can unshift all the objects to your local variable using Array.unshift(obj). this will make your object reverse orders. for an example:- var yourVariableName =[]; firebase.database().ref('books').orderByChild('upvotes').on("child_added", (snapshopt) => { yourVariableName .unshift(snapshopt.val()); }); – Raheem Mohamed May 21 '20 at 01:54
  • you can't get that from firebase ,But you can have them in any order after fetching them and applying sort functions in swift – Harsh Thakur Nov 26 '21 at 13:04

1 Answers1

48

Unfortunately firebase doesn't allow returning by descending order. I have generally just reversed the order of the results returned client side.

If your data query is too large to sort client side you can do

firebase.database().ref('books').orderByChild('ups').limitToLast(2)

and then invert the results from there. Documentation can be seen here

Scott Buckstaff
  • 618
  • 7
  • 10