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 Authenticating users with Remix and Supabase

Authenticating users with Remix and Supabase

·16 min read
Learn how to use Remix and Supabase to authenticate users in your application.
Cover Image for How Makerkit helps boost your SaaS SEO

How Makerkit helps boost your SaaS SEO

·4 min read
Learn how Makerkit can help boost your SaaS SEO thanks to its optimized codebase and SEO-friendly features.
Cover Image for How to sell code with Gumroad and Github

How to sell code with Gumroad and Github

·7 min read
Sell and monetize your code by giving private access to your Github repositories using Gumroad
Cover Image for Migrating to Next.js Server Components Layouts

Migrating to Next.js Server Components Layouts

·6 min read
A simple guide to migrating your _app.tsx component to the new Server Components released with Next.js 13
Cover Image for Getting Started with Next.js Server Components

Getting Started with Next.js Server Components

·8 min read
A simple introduction to using Server Components and the new Layouts Folder Structure with Next.js 13
Cover Image for Pagination with React.js and Firebase Firestore

Pagination with React.js and Firebase Firestore

·6 min read
In this article, we learn how to paginate data fetched from Firebase Firestore with React.js