Home > Back-end >  how to query the subcollections in firestore using flutter?
how to query the subcollections in firestore using flutter?

Time:10-05

I need to query Firestore and the Firestore structure:

root-->payment-->(user IDs)--->(random doc ID)-->(data like paymentid: 1234, paid: 50)
(col)  (doc)       (col)           (doc)              (fields)

My query is like I need to get all values whose paid>0 is my query.

What I have tried is?

var query = FirebaseFirestore.instance;
query.collection("root").where("paid",">",0);

But it didn't return any data and I know this is not the correct format. How can achieve this?

Can even I query this structure using Flutter? or Is there any better structure to implement?

CodePudding user response:

Your actual query won't return the expected result since under the "root" collection there are no documents that contain a "paid" field. There would be however a solution in which you could use a collection group query but only if your subcollection would have had the same name. Since the name of the subcollections are actual user IDs, this solution doesn't apply. So what you can only do is to create a reference that points to a single user:

root-->payment-->(user IDs)

And perform the following query:

var query = FirebaseFirestore.instance
     .collection("root").document("payment")
     .collection(userId).where("paid", ">" ,0);

But this query will only return the documents that correspond to a single user.

Is there any better structure to implement?

Yes, there is. Please check a possible structure below:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid (document)
            |
            --- payments (collection)
                 |
                 --- paymentid: 1234
                 |
                 --- paid: 50

In this way, you can perform a collection group query and get all documents where the "paid" field holds a value greater than 0:

var db = FirebaseFirestore.instance;
var finalQuery = db.collectionGroup("payments").where("paid", ">", 0);
  • Related