Flutter Firestore Query Nested Subcollections - firebase

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.

Related

Firestore Group Collection documents uniqueness

I am trying to do a collection group query from firebase firestore. But I am worried that there might be complications becauase most documents in a subcollection have the same ids as documents in other subCollections. So when I am querying all documents in collection group, I don't know if I will not run into errors or be able to distinguish between the documents.
return _fsInstance
.collectionGroup("subCollection").where('date' isEqualTo: "$date");
A single collection cannot have documents with same IDs but you can have documents with same ID in different (sub)collections. When you run your query, each document in the QuerySnapshot will have its own DocumentReference. For example:
/col/doc/(subCol1)/doc1
/col/doc/(subCol2)/doc1
Here, both subCol1 and subCol2 have document with ID doc1. The query won't cause any issues but when you read doc.id they'll be same.

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
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.

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.

Get non empty Sub Collections in Firestore using Query class

I am trying to get non empty Rooms from Buildings Collection from Firebase Firestore ( Using Flutter Framework):
Query _queryRef = FirebaseFirestore.instance
.collection('Buildings')
.where("isActive", isEqualTo: true)
.where("Rooms", isNotEqualTo : null);
But I am not getting any collections Even though there are few Rooms sub collection records exist in Buildings.
Adding Screenshot for reference-
Queries in Firestore work on a single collection, or on a group of collections of the same name. There is no way to query your Buildings documents on the existence of or values in their Rooms subcollection.
The typical workaround is to store a RoomCount field in each Buildings document, and keep that up to date as you add/remove rooms. With that in place you can query:
FirebaseFirestore.instance
.collection('Buildings')
.where("isActive", isEqualTo: true)
.where("RoomCount", isGreaterThan: 0);
Append .get() at the end of your query. Here you can read more about most common use cases of working with firebase via flutter.

arrayContains in subCollection

Cant seem to understand if arrayContains works on subCollections in Firestore.
This code does not return any data
Firestore.firestore()
.collection("all_chatrooms")
.whereField("postmoderators", arrayContains: userId)
However specifying the targeted collection path does...
Firestore.firestore()
.collection("all_chatrooms")
.document("randomId")
.collection("chatroom")
.whereField("postmoderators", arrayContains: userId)
is there a way to search for an array within subCollections without specifying a documentId?
Do you maybe have to store userIds within a map to be able to search within subColletions?
Firestore queries are shallow, meaning that when you query a specific collection "C1", only the documents from this collection are returned, and not the documents in the subcollections of the documents in "C1".
However, in your case, Collection Group queries may "come to the rescue". As indicated in the doc:
A collection group consists of all collections with the same ID. For
example, if each document in your cities collection has a
subcollection called landmarks, all of the landmarks subcollections
belong to the same collection group.
So if all the docs in the all_chatrooms collection have a subcollection named chatroom you can use a Collection Group query as follows:
Firestore.firestore().collectionGroup("chatroom").whereField("postmoderators", arrayContains: userId)
Of course, by doing so you will get ALL the docs (with userId in postmoderators) in ALL the chatroom subcollections of ALL the docs in the all_chatrooms collection.

Resources