简体   繁体   中英

Firestore - get the parent document of a subcollection

按要求截取我的数据库 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?

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

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);
        }
}

You can write like this

List<DocumentSnapshot> documentSnapshotList = value.getDocuments();
                for (DocumentSnapshot documentSnapshot : documentSnapshotList) {
                    DocumentReference dr = documentSnapshot.getReference().getParent().getParent();
                    // or any field documentSnapshot.get(field);
                    assert dr != null;

                  ));
                } //for end

In case you use stream:

docs = db.collection_group(u'collection_name').stream()
for doc in docs:    
        path = doc.reference.path # will get you the full path
        # then you can manage the path as string
        sub_path = path.split('/')[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM