简体   繁体   中英

Query Document to get snapshots from specific collections in Firestore in Flutter

I am using Firebase Cloud Firestore as the database for my app. The data structure is as below

expenses (collection)

     |____[userId] (doc)

                 |___[year-month] collection

                                |___[expenseId] doc

                                               |______expense fields(amount, date)

How can I get all expenses from a [userId] doc for specific [year-month] collections.

Is there a way to query a doc like we have.where for collection

You have nested collections in your database, right? you can simply chain collection and doc until you get the specific target, since it's not clear what is code variables and what is plain text names, I will assume that all documents and collections names are text, just to so you get the idea:

// This is the reference of a the "year-month" expenses of the user.
Query query = FirebaseFirestore.instance.collection('expenses').doc("userId").collection("year-month");

this will get you a QuerySnapshot containing all documents inside the collection with that "year-month":

QuerySnapshot = await query.get()

You can also get a specific document in that collection like this:

DocumentReference doc = await query.doc("expenseId").get(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM