Firestore - get the parent document of a subcollection

16,552

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

Share:
16,552
Ahmed Nabil
Author by

Ahmed Nabil

Updated on June 13, 2022

Comments

  • Ahmed Nabil
    Ahmed Nabil about 2 years

    Screenshot of my database as requestedI'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?