To solve this, your date should be stored as a Date
object as explained here and not as a number as you say. So to solve this, please change your query to:
firestore.collection("coll_A")
.document("document_A")
.collection("coll_B")
.orderBy("date", Query.Direction.DESCENDING)
.limit(10)
.get()
.addOnCompleteListener(...)
As per Firestore Supported Data Types documentation, you can sort your records chronological
by date and time. Saving the date and time as a ServerValue.TIMESTAMP was useful when using Firebase Realtime database. In the new Cloud Firestore, you need to store the date as a Date
object in order to be able to sort your records according to it. Please see also here informations about ServerTimestamp:
Annotation used to mark a timestamp field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.
So this is the correct way in which you can achieve what you want.
If you are interested, this is how you can update a Date in case you need it.
Edit:
You can order by integers or strings but keep in mind this: When ordering by strings remember that strings are ordered lexicographically while ordering by date
you'll get a chronological order
.
The object that results from setting a Cloud Firestore field with FieldValue.serverTimestamp() is an instance of java.util.Date. When you later read the value, you can get the epoch time using getTime(). This is why Firebase team added this new supported data type, which is more useful then the regular data stored as a number.
If you want to improve your query with more limitation you can use also whereEqualTo()
, whereGreaterThan()
, whereGreaterThanOrEqualTo()
, whereLessThan()
or whereLessThanOrEqualTo()
.
As a conclusion, the best way to store a date is to store it a Date
object.