Skip to content Skip to sidebar Skip to footer

How Can I Query Multiple Different Sub Collection At Ones?

Recently I am building a recipe app. I am using firebase as my database. Now I want to let the users to find any recipe which I have stored in my recipe Collection. Each Food_Recip

Solution 1:

If you want to query several (sub)collections with different names, you will have to use a dedicated query for each of those collections and merge the results.

If you want to avoid that you would need to adapt your data model.

I understand that there are going to be several Food_Recipe documents, since you wrote that "Each Food_Recipe has different subcollections".

So, for example, you could have only one subRecipes subcollection under each Food_Recipe document and, in this subcollection, make the difference between the powder and rice recipes with a field in the document (e.g. a field named recipeType). This way you can use a Collection Group query to query all the subRecipes subcollections, as follows:

Queryquery= FirebaseFirestore.getInstance().collectionGroup("subRecipes").orderBy("Recipe_name").startAt(InputSearchText).endAt(InputSearchText +"\uf8ff");

Note that I called the subcollections subRecipes, since you already have a Recipes root collection.


And if you want to get all the powder recipes for the Food_Recipe document, you filter on the field value, as follows:

Queryquery= FirebaseFirestore.getInstance().collection("Recipes").document("Food_Recipe").collection("subRecipes").whereEqualTo("recipeType", "powder");

More concretely, the proposed data model is the following

-- Recipes (root collection) -- Food_Recipe_1 (document)-- subRecipes (subcollection)-- DocID#1 (document)
            - Recipe_Name: Biriyani (field)
            - recipeType: rice (field)             
            - ....  (field)     
         -- DocID#2 (document)
            - Recipe_Name: Peas Pulao (field)
            - recipeType: rice (field)             
            - .... (field)     
         -- DocID#3 (document)
            - Recipe_Name: Powder Recipe (field)
            - recipeType: powder (field)             
            - ....  (field)     
   -- Food_Recipe_2 (document)-- subRecipes (subcollection)-- DocID#4 (document)
            - Recipe_Name: Another Rice Recipe (field)
            - recipeType: rice (field)             
            - ....  (field)     
         -- DocID#5 (document)
            - Recipe_Name: Another Powder Recipe (field)
            - recipeType: powder (field)             
            - ....  (field)  

Post a Comment for "How Can I Query Multiple Different Sub Collection At Ones?"