Metronom
Metronom

Reputation: 258

Flutter - Fetching a collection from firestore that has multiple sub-collections

Is there any way to retrieve a collection along with its sub-collections from Firebase Firestore using Flutter?

fetchTestSite() async {
    return await FirebaseFirestore.instance
        .collection('sites')
        .doc('4R3aOMBFTjumYCbETDU8')
        .get()
        .then((DocumentSnapshot doc) {
            print('document: ${doc.data()}');
        });
}

This code snippet only returns the main collection without the existing sub-collections

Upvotes: 0

Views: 880

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 1

Is there any way to retrieve a collection along with its sub-collections from Firebase Firestore using Flutter?

No, there is no way you can do that. Queries in Firestore are shallow. This means that it can only return documents from the collection that the query is run against. There is no way to get documents from a top-level collection and sub-collections in a single query. You can only get documents from a single collection.

However, there is a "hack" that can be made. If you want to get the data from the sub-collection that corresponds to a specific document, you can use a collectionGroup to get documents under a certain path. I explained in the following article:

How you can do that and what limitations you might have.

If you consider at some point in time try using the Firebase Realtime Database, what you are looking for it's possible, because when you attach a listener on a specific node, you download all the data beneath it.

Upvotes: 1

Related Questions