【发布时间】:2021-05-18 18:16:09
【问题描述】:
我有 user_info 作为父集合。在这个父集合下,它有 single_list 作为子集合和一些信息。我想从父集合中获取所有值。请帮我找到答案。 提前致谢
【问题讨论】:
标签: android firebase kotlin google-cloud-firestore
我有 user_info 作为父集合。在这个父集合下,它有 single_list 作为子集合和一些信息。我想从父集合中获取所有值。请帮我找到答案。 提前致谢
【问题讨论】:
标签: android firebase kotlin google-cloud-firestore
我认为您对术语的使用有点不对劲。您有一个 user_info 文档的集合,每个文档都有一个名为 single_data 的子集合。
这里的区别在于没有一个 single_data 子集合。每个user_info 文档都有一个子集合。
由于子集合具有静态名称,因此您要做的事情非常简单,使用 collection group query。
firebase.firestore().collectionGroup('single_data')
.get()
.then((querySnapshot) => {
// Do something with the docs from across all the subcollections
})
【讨论】:
collectionGroup() 的概念。确保您的子集合具有一致的名称。
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users_info")
.get()
.addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
//Here you can add all documents Id to your documentIdList to fetch all sigle_data at once.
Log.d(TAG, document.getId() + " => " + document.getData());
documentIdList.add(document.getId());
}
getAllSubCollSingleData(documentIdList);
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
public void getAllSubCollSingleData(List<Int> documentIdList){
for(int i=0;i<documentIdList.size();i++){
db.collection("users_info").document(documentIdList.get(i))(would be phone number)
.collection("single_data")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
//Here you can get all documents in sub collection single_data
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
}}
【讨论】: