I am trying to do pagination with a Firestore database. Is there a way for me to find the number of documents in my Firestore from my website using Javascript so that I can code my (prev) and (next) buttons for pagination accordingly?

- 130,605
- 17
- 163
- 193
-
Is this what you're looking for? https://medium.com/firebase-tips-tricks/how-to-count-documents-in-firestore-a0527f792d04 – sininen Nov 09 '21 at 10:22
1 Answers
(2022-10-20) Edit:
Starting from now, counting the documents in a collection or the documents that are returned by a query is actually possible without the need for keeping a counter. So you can count the documents using the new count() method which:
Returns a query that counts the documents in the result set of this query.
This new feature was announced at this year's Firebase summit. Keep in mind that this feature doesn't read the actual documents. So according to the [official documentation][2]:
For aggregation queries such as count(), you are charged one document read for each batch of up to 1000 index entries matched by the query. For aggregation queries that match 0 index entries, there is a minimum charge of one document read.
For example, count() operations that match between 0 and 1000 index entries are billed for one document read. For A count() operation that matches 1500 index entries, you are billed 2 document reads.
When it comes to Firestore, you can only request pages of data of a particular size using the limit()
function. That being said, you can start from the beginning of a query, and get the following pages of the same size. This operation should continue with other similar operations until there are no more documents left.
So you have to always start from page one, then go forward through the pages using the query cursors, by specifying which document was the last one in the previous query.
Unfortunately, there is no way you can jump between pages. You always have to read all the prior pages. Besides that, since the collections in Firestore don't maintain a document count, you won't be able to know how many pages of data there are ahead of time unless you create and maintain your own count of documents.
If you want to implement a modern way for handling pagination, you should consider implementing that so-called "infinite scroll". Facebook does that, Instagram does that. There are many examples out there.
I have also written an article called:
Where I have explained how you can count documents in Firestore.

- 130,605
- 17
- 163
- 193