[英]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.