I want to get data from my Firestore db ordered by documentId
in descending order. When I call:
firestore.collection("users")
.orderBy(FieldPath.documentId(), Query.Direction.DESCENDING)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {...});
I am getting error:
FAILED_PRECONDITION: The query requires an index.
With a link to Firebase console for automatic index creation. Unfortunately the automatic creation doesn't seem to work in this case. When I click on Create Index I get a message:
__name__ only indexes are not supported
For manual index creation, the doc only says about indexing by field name (not documentId
). Does anyone know how to get data from Firestore ordered by documentId
in descending order?
I know I can re-order data on client side, but ordering by id is such a natural task that I must be missing something. Thank you. I use:
compile 'com.google.firebase:firebase-firestore:11.6.0'
There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.
Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!
As stated in the Firestore document here, Cloud Firestore does not provide automatic ordering on the auto-generated docIDs.
Important: Unlike "push IDs" in the Firebase Realtime Database, Cloud Firestore auto-generated IDs do not provide any automatic ordering. If you want to be able to order your documents by creation date, you should store a timestamp as a field in the documents.
Hence you can achieve ordering by adding an extra field createdDate and just setting it with annotation @ServerTimestamp, declaring it before the class field in your user POJO like this.
@ServerTimestamp
Date createdDate;
Also you must ensure this field is null when the POJO is being written on Firestore, do not set any value to it before saving it on Firestore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With