Get data ordered by document Id descending in Firestore

Viewed 12038

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'
3 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.

The accepted answer here is not correct.

From here:

auto-generated IDs do not provide any automatic ordering.

Yes, because you don't know what the auto-generated ID will be. That does not mean the default sort order is not by id, in fact, another doc page says quite the opposite:

From here:

By default, a query retrieves all documents that satisfy the query in ascending order by document ID. You can specify the sort order for your data using orderBy(), and you can limit the number of documents retrieved using limit().

So yes, you can sort in descending order by document id:

.orderBy(firebase.firestore.FieldPath.documentId(), 'desc')

J

Use this to order in descending order based on id:

.collection("jobs")
.orderBy("", "desc")
Related