Get data ordered by document Id descending in Firestore

11,276

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.

Share:
11,276
zelig74
Author by

zelig74

Updated on June 22, 2022

Comments

  • zelig74
    zelig74 about 2 years

    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'