简体   繁体   English

如何在Firestore中检索子集合的文档?

[英]How to retrieve documents of a sub collection in Firestore?

I have a db with structure like in the image below: 我有一个db结构,如下图所示: 在此输入图像描述

Here, I need to have multiple brands, and also multiple sub brands under each brand. 在这里,我需要拥有多个品牌,每个品牌下还有多个子品牌。 I tried with 'maps' before, but it was really messy and also learned that it's better to have multiple documents. 我之前尝试使用'地图',但它确实非常混乱,并且还了解到拥有多个文档会更好。 I am very new to this and has been struggling with it for 3-4 days now. 我对此非常陌生,现在已经挣扎了3-4天。 Any help would be much appreciated. 任何帮助将非常感激。

  firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if (e != null) {
                Log.d(TAB, "Error : " + e.getMessage());
            }
            for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                if (doc.getType() == DocumentChange.Type.ADDED) {
                    Log.d("Brand Name: ",doc.getDocument().getId());

                  //  how to retrieve documents of subCollection here? something like doc.getDocument().collection??

                }

            }

        }
    });

Thank you. 谢谢。

This is really simple and easy try this. 这非常简单易用。

 firebaseFirestore.collection("Coffee").addSnapshotListener(new EventListener<QuerySnapshot>() {
        @Override
        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
            if (e != null) {
                Log.d("", "Error : " + e.getMessage());
            }
            for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                if (doc.getType() == DocumentChange.Type.ADDED) {
                    Log.d("Brand Name: ", doc.getDocument().getId());
                    doc.getDocument().getReference().collection("SubBrands").addSnapshotListener(new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
                            if (e != null) {
                                Log.d("", "Error : " + e.getMessage());
                            }

                            for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
                                if (doc.getType() == DocumentChange.Type.ADDED) {
                                    Log.d("SubBrands Name: ", doc.getDocument().getId());
                                }
                            }

                        }
                    });
                }

            }
        }});

Note : i have updated the answer. 注意 :我已经更新了答案。 It is obvious that you can't fetch sub collections within the collection's document with a single request. 很明显,您无法使用单个请求获取集合文档中的子集合。

I see that is already an accepted answer but I want to provide you a more elegant way of structuring your database. 我看到这已经是一个公认的答案,但我想为您提供一种更优雅的数据库结构化方法。 This means that you'll also able to retrieve the data more easily. 这意味着您还可以更轻松地检索数据。 Before that, as I understand from your question, you only want to retrieve data but in order to achieve this, just use a get() call. 在此之前,正如我从您的问题中理解的那样,您只想检索数据,但为了实现这一点,只需使用get()调用即可。 addSnapshotListener() is used to retrieve real time data. addSnapshotListener()用于检索real time数据。

This is the database structure that I suggest you use for your app: 这是我建议您用于应用程序的数据库结构:

Firestore-root
   |
   --- coffee (collection)
         |
         --- coffeeId (document)
                |
                --- coffeeBrand: "Nescafe"
                |
                --- coffeeSubBrand: "Sunrise"
                |
                --- coffeeName: "CoffeeName"
                |
                --- quantity
                       |
                       --- 50g: true
                       |
                       --- 100g: true
                       |
                       --- 150g: true

While Nouman Ch's code might work on your actual database structure, this new structure will provide you the ability to avoid nested loops. 虽然Nouman Ch的代码可能适用于您的实际数据库结构,但这个新结构将为您提供避免嵌套循环的能力。 To get all the coffees, just use the following code: 要获得所有的咖啡,只需使用以下代码:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference coffeeRef = rootRef.collection("coffee");
coffeeRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                String coffeeName = document.getString("coffeeName");
                Log.d("TAG", coffeeName);
            }
        }
    }
});

If you want to display only the Nescafe coffee , instead of using a CollectionReference , you need to use a Query : 如果您只想显示Nescafe coffee ,而不是使用CollectionReference ,则需要使用Query

Query query = coffeeRef.whereEqualTo("coffeeBrand", "Nescafe");

If you want to display only the coffee SubBrands then use the following Query: 如果您只想显示咖啡SubBrands,请使用以下查询:

Query query = coffeeRef.whereEqualTo("coffeeSubBrand", "Sunrise");

If you want to display the coffees Brands and SubBrands, you can chain methods like this: 如果你想显示咖啡品牌和子品牌,你可以链接这样的方法:

Query query = coffeeRef
    .whereEqualTo("coffeeSubBrand", "Sunrise")
    .whereEqualTo("coffeeBrand", "Nescafe");

If you want to display only the coffee with the quantity of 100g , then just use the following query: 如果您只想显示数量为100g的咖啡,请使用以下查询:

Query query = coffeeRef.whereEqualTo("quantity.100g", true);

If you want to learn more about Cloud Firestore database structures, you can take a look on one of my tutorials . 如果您想了解有关Cloud Firestore数据库结构的更多信息,可以查看我的一个教程

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

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