Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data ordered by document Id descending in Firestore

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'
like image 728
zelig74 Avatar asked Nov 22 '17 14:11

zelig74


People also ask

How do I get specific data from firestore?

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.

How do I get most recent documents on firestore?

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!


1 Answers

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.

like image 149
Dhara Bhavsar Avatar answered Sep 20 '22 12:09

Dhara Bhavsar