firebasegoogle-cloud-firestore

Firestore: Getting collection with and without its sub-collection data


I have collection of charracters where each document has some public data like username and character level, but also a private sub collection that has things like that characters gold amount.

Right now I can query characters collection for a specific document, but sub-collection data is not returned, so I need to perform a secondary query to retrieve it.

Is this the most optimal way to achieve this or is there a way to indicate that I also want to receive sub-collection data in the first query and sort of merge them together?


Solution

  • Queries in Firestore are always shallow. There is no way to get documents from a parent document and its subcollections with a single query. So if you need to read from the subcollection, it will indeed at a minimum require two queries/read operations.

    If you want to read from all those private subcollection that can be accomplished with a collection group query. This type of query reads from all collections with a specific name.