2

i have a collection "Store"

in that having number of documents

how i get the count of documents in that collection.

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
Ramakrishna
  • 43
  • 1
  • 5

1 Answers1

7

I believe there is no built in method for this but you can try this! First get all the documents in a List and then just get the size.

  db.collection("Store")
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
               int count = 0;
                for (DocumentSnapshot document : task.getResult()) {
                   count++;
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

Src:get data with Firestore

Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • i am getting errors at ApiFuture and future.get() – Ramakrishna Dec 12 '17 at 10:57
  • @Ramakrishna edited, accidenetly chose java code for query instead of android appearantly this should work, db is your database instance, count is your document count , or if you don't get smth check the link with docs – Rainmaker Dec 12 '17 at 12:07
  • 9
    Don't need to run loop use this task.getResult().size() – saurabh dixit Jan 19 '18 at 12:11
  • Can you help me with this question please https://stackoverflow.com/questions/54653836/how-to-use-query-in-firebase-firestore – Rajesh K Feb 12 '19 at 18:40
  • this approach is not cost-efficient. It will read all document. Why read all documents when we need just count. – Vikash Sharma Jun 06 '20 at 10:51
  • @VikashSharma ask Google, as the answer states there is no api for this that is provided out of the box – Rainmaker Jun 06 '20 at 20:22
  • @Rainmaker this approach is very expensive. We should add transaction for counting documents. This way we won't be reading all the documents all the time just to get count. – Vikash Sharma Jun 07 '20 at 13:52
  • 1
    @VikashSharma if I am sure what you mean, please post your suggestion as a stand alone answer so It can help people if it is more optimized u feel – Rainmaker Jun 08 '20 at 14:10
  • @Rainmaker https://stackoverflow.com/a/62270141/7011829 – Vikash Sharma Jun 08 '20 at 19:52
  • In that case I will have to pay for each reading returned even if I do nothing in the snapshots besides counting? – DjongaNelson Lontrowski Dec 02 '20 at 18:32
  • @DjongaNelsonLontrowski yes, but even if there was a api to just get count how do you think it would work? It would still be some resource used to get the number of rows in the table on disk. Disk operation (if you write something, read or count rows) all have some cost. – Rainmaker Dec 03 '20 at 14:53
  • Is there a way for finding out in kotlin? – Adan Vivero Dec 17 '21 at 23:50