繁体   English   中英

Firestore - 获取子集合的父文档

[英]Firestore - get the parent document of a subcollection

按要求截取我的数据库 我正在开发一个使用具有以下层次结构的 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
                        }
                    }
                });

实现这一目标的最佳方法是什么?

QuerySnapshot指向许多QueryDocumentSnapshot实例。

QueryDocumentSnapshot ,您可以获取它的集合:

snapshot.getRef().getParent()

然后父DocumentReference是:

snapshot.getRef().getParent().getParent()

所以要获得父文档的子集合:

snapshot.getRef().getParent().getParent().collection("name_of_subcollection")

是的,我同意......这可能更具可读性。 :)

您可以获得如下集合的文档:

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

你可以这样写

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

如果您使用流:

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