Have you ever tried to fetch the number of documents from a Firebase collection? Maybe you needed to know how many users you app had, or how many registered tasks were in total.

Only to know that Firestore doesn’t have a .count() method, which means that to get the total number of documents on a collection we’d have to fetch that collection and then verify its length.

This can become problematic really fast, because depending on the size of your documents, once you pass a couple of hundred documents in a collection you’ll start hitting performance and memory limits.

But, what if there was another way? Some way you could just call one thing and get that data that you need?

That’s where statistical documents come from, and it’s not something exclusive to Firestore, it’s the practice of storing all the metadata you need for statistics inside one stats document.

For example, let’s say you have an application were users start as free and then can upgrade down the road.

3 things you always want to know is:

  • How many users you have in total.
  • How many users are free users.
  • And how many users upgraded to paid users.

For that, in our users collection we could create a document with the ID of ----stats----, and store the information there through our Cloud Functions.

So your users collection could have a matching Cloud Function that triggered with an .onCreate(), this means that every time you add a new user document to the users collection this function would trigger itself.

That function could add +1 to the number of total users and +1 to the number of free users in the ----stats---- document.

And later in your upgrade or payment business logic, you could also update this ----stats---- document to remove one from the free users and add +1 to the paid users.

In the end you could have a document that looked like this:

{
  "----stat----": {
    "totalUsers": 600,
    "freeUsers": 380,
    "paidusers": 220
  }
}

That way when you need to get one of those numbers, you can do a quick fetch like:

constructor(firestore: AngularFirestore) {}

getTotalUsers() {
  return this.firestore.doc('users/----stats----').valueChanges();
}

Which would return the data you need, without needed to loop through your entire data list to get it 🤓.

The one thing to always remember and keep in mind is to ALWAYS keep that document updated, so if any business logic on your application, adds, removes, or upgrades users, the stats document needs to be updated.