Skip to content Skip to sidebar Skip to footer

Cloud Firestore Get Collection By Reference From Another Collection

I have a collection called Products and another one named Category. Products document has a field idCategory, referencing category's id. I want to get all documents from Products w

Solution 1:

I want to get all documents from Products where the category name is equals "Soda".

Because you don't have all data in a single document, you need to query your database twice. Once to get the id of the category which is "Soda" in this case and then based on that id get the corresponding products. This is because Firestore doesn't support queries across multiple collections. A single query may only use properties of documents in a single collection.

By why to query the database twice, which is aslo costly when you can query once and get the desired documents. For that, you need to make a little change in your database schema. Since a single product may belong to multiple categories, your new schema should look like this:

Firestore-root
    |
    --- products (collection)
          |
          --- productId (document)
                |
                --- productName: "Soda Water"
                |
                --- category: ["Soda", "Other Category"]
                |
                --- //Other properties

To get all document that are apart of Soda category, please use the following lines of code:

FirebaseFirestorerootRef= FirebaseFirestore.getInstance();
CollectionReferenceproductsRef= rootRef.collection("products");
Queryquery= productsRef.whereArrayContains("category", "Soda");

Edit: You can also hold references instead of only ids but for that, please see my answer from this post.

Solution 2:

It looks like you would do a simple query (Firebase Docs Reference):

FirebaseFirestoredb= FirebaseFirestore.getInstance();

CollectionReferenceproductsRef= db.collection("Products");

Queryquery= productsRef.whereEqualTo("idCategory", "Soda");

query.get()
.addOnSuccessListener(newOnSuccessListener<QuerySnapshot>() {
    @OverridepublicvoidonSuccess(QuerySnapshot queryDocumentSnapshots) {
        /// do things with response
    }
})
.addOnFailureListener(newOnFailureListener() {
    @OverridepublicvoidonFailure(@NonNull Exception e) {
        /// do things with error
    });

Post a Comment for "Cloud Firestore Get Collection By Reference From Another Collection"