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:
- Reverse the nodes on the client.
- 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:
- order on timestamp
- get the last 10 items
- reverse them client-side
Also see:
- How to get data from firebase in descending order of value?, which shows an example of storing an inverted score.
-
Sorting in descending order in Firebase database, which shows someone using the
limitToLast
approach mentioned above. -
Display posts in descending posted order, which shows how to invert a date value. Please ignore the use of priorities, as you'd nowadays just store the inverted value in a regular property and use
orderByChild()
. - Many more links from this list.
Author by
dfdfdsfsd
Updated on December 16, 2022Comments
-
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 over 4 yearsI 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 over 4 yearsThat 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/…