How to get a count of number of documents in a collection with Cloud Firestore

justinbc820 picture justinbc820 · Oct 3, 2017 · Viewed 32.7k times · Source

In Firestore, how can I get the total number of documents in a collection?

For instance if I have

/people
    /123456
        /name - 'John'
    /456789
        /name - 'Jane'

I want to query how many people I have and get 2.

I could do a query on /people and then get the length of the returned results, but that seems a waste, especially because I will be doing this on larger datasets.

Answer

Dan McGrath picture Dan McGrath · Oct 4, 2017

You currently have 3 options:

Option 1: Client side

This is basically the approach you mentioned. Select all from collection and count on the client side. This works well enough for small datasets but obviously doesn't work if the dataset is larger.

Option 2: Write-time best-effort

With this approach, you can use Cloud Functions to update a counter for each addition and deletion from the collection.

This works well for any dataset size, as long as additions/deletions only occur at the rate less than or equal to 1 per second. This gives you a single document to read to give you the almost current count immediately.

If need need to exceed 1 per second, you need to implement distributed counters per our documentation.

Option 3: Write-time exact

Rather than using Cloud Functions, in your client you can update the counter at the same time as you add or delete a document. This means the counter will also be current, but you'll need to make sure to include this logic anywhere you add or delete documents.

Like option 2, you'll need to implement distributed counters if you want to exceed per second