Firestore document count estimator


If you use Firestore’s built-in add method, you can get a rough estimate of the number of documents in a collection1 by providing a relatively small number of consecutive document IDs.2

Follow these steps to got an “order of magnitude” estimation of the number of documents in a large collection3:

  1. We need to get the first 100-2004 document IDs in the collection.
  2. Go to the Firestore query builder
  3. Hide all fields from the results, which leads just the document ID5
  4. Drag while holding the mouse button to select all document IDs, and copy them
  5. Paste the document IDs below (or paste some of my test data)
  6. Tab out of or click outside the text area

Based on the values above there are an estimated ??? documents in the collection (group).

Footnotes

  1. While Firestore nowadays has a dedicated API for counting results, this can in my testing only handle results into the 10s of millions, and also become expensive (counting 10 million documents costs 10 thousand document reads). While the approach used in this page only gives an estimate of the document count, it as a fixed cost (of 100-200 document reads). For what counter approach to use in what scenarios, see How to handle aggregated values in Firestore

  2. I first learnt about this approach from original Firestore product manager Dan McGrath, but I can’t find any write-up of his about it.

  3. To learn more about this approach, see Estimate Firestore collection count from a small sample of documents where I also got most of the code that this page uses. Thanks jfhr! 🙏

  4. For a collection with 22,833 the estimate based on the first 100 IDs was 19,155 documents (so off by 17%). With 200 IDs the estimate became 20,326 document (so off by 11%). Both are a bit further off than I recalled, but well within range for my needs - YMMV of course

  5. On Datastore (and Firestore and Datastore more) this sort of keys-only query can be performed for the cost of one entity read, but Firestore in native mode unfortunately doesn’t have such an option (yet).

Magic pixel View count: