1
votes

In Firestore, how can I get the total number of documents and the id's of these in a collection?

For instance if I have

/Usuarios
    /Cliente
        /JORGE
            /456789
                /filtros
                      /status
                          /activo
                          /inactivo

My code:

FirebaseFirestore db = FirebaseFirestore.getInstance();
Task<QuerySnapshot> docRef = db.collection("Usuarios").document("Cliente").collection("JORGE").document("filtros").collection("status").get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            int contador = 0;
                            for (DocumentSnapshot document: task.getResult()) {
                                contador++;
                            }

                            int cantPS = contador;
}

I want to query how many people I have and get: 2 and the id's: activo, inactivo.

1
Check also this out. - Alex Mamo

1 Answers

0
votes

To determine the number of documents returned by a query, use QuerySnapshot.size().

To get the list of documents returned by a query, use QuerySnapshot.getDocuments().

To show the key of a document use DocumentSnapshot.getId().

So in total:

public void onComplete(@NonNull Task<QuerySnapshot> task) {
    if (task.isSuccessful()) {
        QuerySnapshot querySnapshot = task.getResult();
        int count = querySnapshot.size();
        System.out.println(count);
        for (DocumentSnapshot document: querySnapshot.getDocuments()) {
            System.out.println(document.getId());
        }
    }
}