Home > Back-end >  How to get documents of a collection having a specific subcollection in Firestore?
How to get documents of a collection having a specific subcollection in Firestore?

Time:01-28

For a Flutter project my Firestore structure looks like this:

posts(collection) --> document1
                  --> document2 --> applications(sub-collection)
                  --> document3
                  --> document4 --> applications(sub-collection)
                  --> document5

I want to get the documents which have applications sub-collection, in this example document2 & document4. How to do this?

enter image description here

CodePudding user response:

You may want to run two get queries to get both querysnapshot(s)

db.collection('posts').doc('document2').collection('applications').get()
db.collection('posts').doc('document4').collection('applications').get()

Then merge both results into a single List<QuerySnapshot> and parse your result as you see fit.

CodePudding user response:

As Timothy said in his answer, one option is to perform a separate read for each subcollections, and then merge them in your application code.

Alternatively you can use a collection group query (Flutter docs) to read from all applications collections at once. There is no way to limit such a read to just document2 and document4 though, so this only works if those are the only applications collections in your database.

  •  Tags:  
  • Related