How to order documents by timestamp automatically in firebase?

1,902

Firebase Realtime Database always returns results in ascending order. There is no way to order descending order.

This means you have two common options:

  1. Reverse the nodes on the client.
  2. Store an inverted value in a property, and order on that.

If you want to retrieve a subset of the items, keep in mind that you can combine any of these approaches with limitToFirst() and limitToLast. For example, to get the 10 most recent messages, you could:

  1. order on timestamp
  2. get the last 10 items
  3. reverse them client-side

Also see:

Share:
1,902
dfdfdsfsd
Author by

dfdfdsfsd

Updated on December 16, 2022

Comments

  • dfdfdsfsd
    dfdfdsfsd over 1 year

    I've created an app and I am using firebase as well but I want to order the documents by timestamp such that my documents will be ordered from recently added ones to older ones.

    I wonder if there is a solution rather than using orderBy method because my project is very big.

    please help me.

    Note: I am devolping the app using flutter & dart.

  • dfdfdsfsd
    dfdfdsfsd over 4 years
    I did as you have mentioned above and I've created a field called time and it is equal to DateTime.now() (Dart) but it orders according to the current time of the users so this makes a disturbance in my app especially in chats
  • Frank van Puffelen
    Frank van Puffelen over 4 years
    That sounds like a new problem problem to me. But if you want to have a consistent timestamp that is not dependent on the client-side click, use ServerValue.timestamp. Read more about it in the documentation here: firebase.google.com/docs/database/android/…