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

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

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 to query collections in Firestore under a certain path?
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.

Related

Read data from firebase document with sub collections >> sub documents

Is it possible to get data of sub-documents by reading only the main document in Firestore? Basically, the Firebase listCollections() method gives the id of subcollections, but how can we get their data?
I have tried for listCollections() to get the id of sub-collections, but have not found a way to get data sub-collections data.
Is it possible to get data of sub-documents by reading only the main document in Firebase?
In Firestore, the queries are shallow. This means that it can only return documents from the collection that the query is run against. So there is no way you can get documents along with the data that exists inside sub-collections in one go. A single query can only read fields of documents in a single collection.
If you need to get documents from sub-collection, you need to perform separate queries. If you have collections or sub-collections that have the exact same name then you can use a collection group query.
Firebase listCollectionIds(),Firebase listDocuments() are well documented by firebase but nobody use and write on it....
I think the best way is to list subcollection to your document throught the well-know get() and then process a foreach on result snapshot
snapshot.forEach(doc =>{
console.log(doc.id)
console.log(doc.data())
})

How to make a query from a nested collection in firestore using flutter

I have a nested collection in firestore that I want to make a query from it.
As you can see the first collection called 'businessUsers' and the nested one called 'campaigns',
If I make a query for a field in the 'businessUsers' it's working OK:
return FirebaseFirestore.instance.collection("businessUsers").where('xxx',
isEqualTo:filterBusinessResult ).snapshots().map(_businessListFromSnapshot);
but how can I make a query to 'campaigns' collection field?
I tried
return FirebaseFirestore.instance.collection("businessUsers").doc().collection("campaigns").where('campaignCategory', isEqualTo:filterBusinessResult ).snapshots()
.map(_businessListFromSnapshot);
but it wont work.
Its important to note, that I need all the data with 'campaignCategory' == filterBusinessResult
any idea?
It depends on whether you want to query a specific user's campaigns, or the campaigns of all users together.
If you want to query the campaigns of a specific user, you need to query under their document:
FirebaseFirestore.instance
.collection("businessUsers").doc("your user ID").
.collection("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
So you have to know the ID of the businessUsers document here.
If you want to query across all campaigns subcollections are once, that is known as a collection group query and would look like this:
FirebaseFirestore.instance
.collectionGroup("campaigns")
.where('campaignCategory', isEqualTo:filterBusinessResult)
The results are going to documents from the campaigns collection only, but you can look up the parent document reference for each DocumentSnapshot with docSnapshot.reference.parent.parent.
When querying something, .doc() requires the id of the document you're trying to get. So it's failing because it doesn't know which document in the businessUsers collection you're trying to fetch a subcollection on. You probably want to use a .collectionGroup() query here. They let you query all subcollections at once (see documentation here). With FlutterFire specifically, it's going to be something like:
var snapshots = FirebaseFirestore.instance.collectionGroup("campaigns")
.where("campaignCategory", isEqualTo: filterBusinessResult)
.snapshots();

Fetch data from subcollection document in flutter

This is my data structure. Here are the list of users documents.
and here is the subcollection in every document.
The subcollection is containing strongly typed document which is form.
What I want is to fetch form document (not for the current user) from subcollection workerField from every users document.
what is the implementation method.
If you want to load documents from all workerField collections you can use a so-called collection group query.
So something like:
var docs = await FirebaseFirestore.instance
.collectionGroup('workerField')
.snapshots();
See my answer here for another example: Is wildcard possible in Flutter Firestore query? and more from these search results.

Query Firebase Firestore Subcollection in Flutter

I am querying my Firestore database as follows:
final Query roasters = Firestore.instance
.collection('retailers')
.where('retail_category', isEqualTo: 'Coffee Roasters');
I am receiving the result back of all documents in the retailers collection which have 'retail_category' set as 'Coffee Roasters'.
The Problem
I instead want to turn retail_category into a separate collection and instead reference it in the retailer field (which would negate the following reference):
"retail_categories/hEN5fzNl2hEc2tEs05Wi"
I have tried the following:
final Query roasters = Firestore.instance
.collection('retailers')
.where('retail_categories', isEqualTo: ' qretail_categories/hEN5fzNl2hEc2tEs05Wi');
Here is my Firestore configuration:
Retailers
Retail Categories
It's not possible to reference data in documents outside of the collection being used for the query. For this reason, it's very common to duplicate data between documents that need to be used in queries for each collection. If you don't want to do that, you will have to make separate queries for each referenced document.

Flutter Firestore Query Nested Subcollections

I am trying to query subcollection in Firebase, but I always get an empty list...
This is my query:
Firestore.instance.collection('messages').where('idFrom', isEqualTo: userID).snapshots();
I know that I have subcollection with another subcollection here..
/messages/RWzG98s92mVTZniofez6YoYsNhA3-tT2Q16n1FMZoTNZQOejtWuJdCmD2/RWzG98s92mVTZniofez6YoYsNhA3-tT2Q16n1FMZoTNZQOejtWuJdCmD2/1579394957103
And my question is how to query these types of models?
Since Firstore queries are always shallow, you have to build the path to the subcollection to query.
Firestore.instance
.collection('messages')
.document(...) // ID of the nested document
.collection(...). // ID of the nested subcollection
.where('idFrom', isEqualTo: userID);
There is no way to avoid giving those nested IDs. If you can't identify the full path of the subcollection to query, you won't be able to access its documents.

Resources