I'm working on an app that uses a firestore database with the following hierarchy: parent_collection: parent_document: subcollection: child_document{ string name} using collectionGroup I've been able to query subcollection for documents with a certain name, but I don't know how to get the parent_document
db.collectionGroup("subcollection").whereEqualTo("name", searchText).get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if(task.isSuccessful()){ //here I want to get the parent id of all results } } });
What is the best way to achieve that?
You can either go to Firestore Databases > Indexes console and do it, or use the firebase cli. But the easiest option is to just let your code (that performs the query) run and firestore will automatically error out when an index is missing.
A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).
There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.
A collection contains documents and nothing else. It can't directly contain raw fields with values, and it can't contain other collections. (See Hierarchical Data for an explanation of how to structure more complex data in Cloud Firestore.)
The QuerySnapshot
points to a number of QueryDocumentSnapshot
instances.
From a QueryDocumentSnapshot
, you can get the collection it's from with:
snapshot.getRef().getParent()
And then the parent DocumentReference
is:
snapshot.getRef().getParent().getParent()
So to get a subscollection of the parent document with:
snapshot.getRef().getParent().getParent().collection("name_of_subcollection")
Yes, I agree... that could've been a bit more readable. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With