Counting a collection's documents with Firebase Firestore

In this article, we learn how to count the number of documents in a Firestore collection using a custom React.js hook.

·2 min read
Cover Image for Counting a collection's documents with Firebase Firestore

During the 2022 Firebase Submit, the Firebase team released a huge new feature for Firestore: count aggregations.

Thanks to count aggregations, we can query the total number of documents in a Firestore collection.

To do so, we are going to use the function getCountFromServer: this function accepts a Firestore query and will return the number of documents found according to the query.

A Custom React hook to fetch the documents count from Firestore

In the example, below, we use React.js and Firebase to fetch the number of documents contained in our Firestore collection tasks:

import { useCallback } from 'react';
import { useFirestore } from 'reactfire';

import {
  where,
  getCountFromServer,
  query,
  collection,
  CollectionReference,
} from 'firebase/firestore';

import { Task } from '~/lib/tasks/types/task';

const tasksCollection = 'tasks';
const path = `organizationId`;
const operator = '==';

function useFetchTasksCount() {
  const firestore = useFirestore();

  return useCallback(
    (organizationId: string) => {
      const constraints = [
        where(path, operator, organizationId)
      ];

      const collectionRef = collection(
        firestore,
        tasksCollection
      ) as CollectionReference<WithId<Task>>;

      return getCountFromServer(
        query(collectionRef, ...constraints)
      );
    },
    [firestore]
  );
}

export default useFetchTasksCount;

Now that we have a React hook that returns a function to fetch the number of documents from the collection, we can use this custom hook in one of our components and render the result:

function TasksCollectionCount(
  props: React.PropsWithChildren<{
    organizationId: string
}>) {
  const fetchTaskCount
    = useFetchTasksCount();

  const [tasksCount, setTasksCount]
    = useState<number>();

  useEffect(() => {
    // when the component mounts, we store the tasks count in the state
    fetchTaskCount(props.organizationId).then((result) => {
      setTasksCount(result.data().count);
    });
  }, [fetchTaskCount, props.organizationId]);

  if (tasksCount === undefined) {
    return <p>Loading count...</p>;
  }

  return <div>Tasks ({ tasksCount })</div>;
}

Great, we can now display how many tasks are in our tasks collection for the organization.

Billing for Firestore Count Aggregations

When you query aggregated data using the count aggregations, every 1000 documents counted will count as 1 document read.


Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor

Read more about

Cover Image for Next.js 13: complete guide to Server Components and the App Directory

Next.js 13: complete guide to Server Components and the App Directory

·11 min read
A tutorial on how to use Next.js 13 with server components and the app directory.
Cover Image for Pagination with React.js and Supabase

Pagination with React.js and Supabase

·6 min read
In this article, we learn how to paginate data with Supabase and React.js
Cover Image for How to sell code with Lemon Squeezy and Github

How to sell code with Lemon Squeezy and Github

·7 min read
Sell and monetize your code by giving private access to your Github repositories using Lemon Squeezy
Cover Image for Writing clean React

Writing clean React

·9 min read
Learn how to write clean React code using Typescript with this guide.
Cover Image for How to use MeiliSearch with React

How to use MeiliSearch with React

·12 min read
Learn how to use MeiliSearch in your React application with this guide. We will use Meiliseach to add a search engine for our blog posts
Cover Image for Setting environment variables in Remix

Setting environment variables in Remix

·3 min read
Learn how to set environment variables in Remix and how to ensure that they are available in the client-side code.