Iterate through sub collections to get fields - Firestore Android

Viewed 7028

Each Notification ID collection contain only one document and I want to Iterate all the collections in ToseefShop1 and get the respective document name and fields data.

Data Model:

enter image description here Sub Collections:

enter image description here enter image description here Code:

dbRef.collection("Shop Notifications")
        .document("ToseefShop1")
        .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot querySnapshot) {
        // Dont know what to do
    }
});

It's not a duplicate question. The other question (someone suggested as duplicate to) is about javascript and answers are for Node.js. With no answer accepted. Infact I can not find getcollections() method in firestore Java.

3 Answers

There is no way in Firestore to query a document to get the subcollections beneath it. In order to get the document name and fields data that you are asking for, first you need to have the names of subcollections and then use them in a reference. If you have only 2 subcollections, I suggest you to use the following code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query firstQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:0");
Query secondQuery = rootRef
    .collection("Shop Notifications")
    .document("ToseefShop1")
    .collection("Notification ID:1");

Task firstTask = firstQuery.get();
Task secondTask = secondQuery.get();

Task combinedTask = Tasks.whenAllSuccess(firstTask, secondTask).addOnSuccessListener(new OnSuccessListener<List<Object>>() {
    @Override
    public void onSuccess(List<Object> list) {
         //Do what you need to do with your list
    }
});

There is no way (with the Android/iOS/JavaScript SDKs) to get the list of (sub)-collections of a document. You have to know the collections' identifiers in order to access them.

From the comments attached to the question I understand that the sub-collection identifiers will be different for each document (and probably their number too). Therefore, one workaround could be to maintain a list of sub-collections' identifiers in the parent document (e.g. as a field of type array).

You can use a Cloud Function to list all the subcollections of a given document.

Read Approach #2: Use a Cloud Function

At the middle of the page.

Approach #1: Save the list in a dedicated field of the parent document

Is very similar to the other answers here, but you probably want the second approach much more than the first approach, because the second approach is much more efficient, productive, cheaper and your database is much more easier to maintain than the first approach.

Related