I have a collection and Subcollection, I want to get the data of subcollection along with main collection data. I am using collectionGroup query, but don't know how to get subcollection's data.
Below is Screenshot and the code.
Below is my future function of getting Querysnapshot.
Future<void> getCollectionData() async {
await FirebaseFirestore.instance
.collectionGroup('testsub')
.get()
.then((QuerySnapshot snapshot) {
final docs = snapshot.docs;
for (var data in docs) {
print(data.data()); // Output: {main1: it is main1, main2: it is main2}
}
});
}
CodePudding user response:
Firestore queries read from a single collection only, or from all collections with a given name. There is no way to include information from other (sub)collections within the same read operation.
So you will have to perform a separate read operation to get the information from the subcollections.
In some cases it may be possible to replicate the necessary information from the subcollections in the parent document, but that really depends on your use-case and the amount of data you expect.
CodePudding user response:
A collection group consists of all collections with the same ID.
Therefore the collection group should be pointing to your sub-collection 'testsubc'.
So your code should be;
Future<void> getCollectionData()
async {
await FirebaseFirestore.instance
.collectionGroup('testsubc')
.get()
.then((QuerySnapshot
snapshot) {
final docs = snapshot.docs;
for (var data in docs) {
print(data.data()); //
Output: {main1: it is main1 sub,
main2: it is main2 sub}
}
});
}