Skip to content
Advertisement

get data with query from document collection and document subcollection in firestore

I have a collection with “grup” name and have a subcollection named “anggota”.

Please help me, how to display data by query referring to collection document and subcollection document.

Firestore collection:

collections in my firestore

I’ve tried with this query but it doesn’t work, the data doesn’t appear

db.collection("grup").document().collection("anggota")
            .whereEqualTo("iduser", idUser)
            .orderBy("updatetime", Query.Direction.DESCENDING)
        .addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                List<DocumentSnapshot> list = value.getDocuments();

                datalist.clear();
                for (DocumentSnapshot d : list) {
                    final Modelfirestore c = d.toObject(Modelfirestore.class);
                    datalist.add(c);
                    
                }
                mAdapterss.notifyDataSetChanged();
            }
        });

Answer

When you are using the following query:

                              👇
db.collection("grup").document().collection("anggota")
        .whereEqualTo("iduser", idUser)
        .orderBy("updatetime", Query.Direction.DESCENDING)

It means that you are creating a reference to a document with a random ID. Calling CollectionReferenc#document() method, without passing any arguments:

Returns a DocumentReference pointing to a new document with an auto-generated ID within this collection.

So to be able to query the documents within the anggota subcollection you have to pass the document ID to the document() method like this:

                                 👇
db.collection("grup").document("8FDD...").collection("anggota")
        .whereEqualTo("iduser", idUser)
        .orderBy("updatetime", Query.Direction.DESCENDING)
Advertisement