Firestore - get the parent document of a subcollec

2020-07-03 04:13发布

问题:

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?

回答1:

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



回答2:

You can get documents of a collection like this:

if(task.isSuccessful()) {
        List<DocumentSnapshot> documents = task.getResult().getDocuments();
        for(DocumentSnapshot documentSnapshot : documents) {
            documentSnapshot.getId();
            // or any field documentSnapshot.get(field);
        }
}