Firestore - get the parent document of a subcollection
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. :)
![Ahmed Nabil](https://lh5.googleusercontent.com/-p9s9Xu0JF9c/AAAAAAAAAAI/AAAAAAAAABU/r_jJeRSGa9A/photo.jpg?sz=256)
Ahmed Nabil
Updated on June 13, 2022Comments
-
Ahmed Nabil about 2 years
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?