LMaker
LMaker

Reputation: 1620

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 where the category name is equals "Soda".

How can I do that?

Upvotes: 1

Views: 4100

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138834

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:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference productsRef = rootRef.collection("products");
Query query = productsRef.whereArrayContains("category", "Soda");

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

Upvotes: 2

AnxGotta
AnxGotta

Reputation: 1006

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

FirebaseFirestore db = FirebaseFirestore.getInstance();

CollectionReference productsRef = db.collection("Products");

Query query = productsRef.whereEqualTo("idCategory", "Soda");

query.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
        /// do things with response
    }
})
.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        /// do things with error
    });

Upvotes: 0

Related Questions