简体   繁体   English

Firestore - 获取子集合的父文档

[英]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我正在开发一个使用具有以下层次结构的 firestore 数据库的应用程序: parent_collection: parent_document: subcollection: child_document{ string name} using collectionGroup 我已经能够查询具有特定名称的文档的子集合,但我没有知道如何获取 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. QuerySnapshot指向许多QueryDocumentSnapshot实例。

From a QueryDocumentSnapshot , you can get the collection it's from with: QueryDocumentSnapshot ,您可以获取它的集合:

snapshot.getRef().getParent()

And then the parent DocumentReference is: 然后父DocumentReference是:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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