Firestore collection group queries - how to order parent documents the subcollections are part of?

Viewed 400

I have the following data structure:

collection/
    parent_document_1/
        timestamp: 0
        subcollection/
            document/
                belongsTo: parent_document_1
                data: data
    
    parent_document_2/
        timestamp: 0
        subcollection/
            document/
                belongsTo: parent_document_1
                data: data

    parent_document_3/
        timestamp: 0
        subcollection/
            document/
                belongsTo: parent_document_1
                data: data

I want to sort parent_documents by their timestamp property, then make a collectionGroup query on the subcollection collection. I do not want to add an additional property to documents because the timestamp value under parent_documents is the ONLY value I want to sort on. The reason for this is that documents can be duplicates of one another, and timestamp needs to be updated for each parent_document individually.

The bigger picture is that I want to be able to query say, only the 3-5 most recently updated subcollections.

Is this possible to do with Firestore?

1 Answers

You don't have an alternative to copying the timestamp into the documents in the subcollection that you want to query.

With Firestore, when you query a collection or collection group, you can only use fields immediately within the documents of those collections. You can not reach out and use fields in documents in other collections - this includes both "parent" and "child" documents. There are no SQL-like "joins" between documents in different collections.

Related