• Blog
  • Documentation
  • Courses
  • Changelog
  • AI Starters
  • UI Kit
  • FAQ
  • Supamode
    New
  • Pricing

Launch your next SaaS in record time with Makerkit, a React SaaS Boilerplate for Next.js and Supabase.

Makerkit is a product of Makerkit Pte Ltd (registered in the Republic of Singapore)Company Registration No: 202407149CFor support or inquiries, please contact us

About
  • FAQ
  • Contact
  • Verify your Discord
  • Consultation
  • Open Source
  • Become an Affiliate
Product
  • Documentation
  • Blog
  • Changelog
  • UI Blocks
  • Figma UI Kit
  • AI SaaS Starters
License
  • Activate License
  • Upgrade License
  • Invite Member
Legal
  • Terms of License

Counting a collection's documents with Firebase Firestore

Oct 21, 2022

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

firebase

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:

tsx
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:

tsx
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.

Some other posts you might like...
Dec 17, 2022How to reduce and boost your Firebase cold start timesFirebase cold start times are a common problem for developers. In this tutorial, we'll show you how to reduce and boost your Firebase cold start times.
Oct 21, 2022Pagination with React.js and Firebase FirestoreIn this article, we learn how to paginate data fetched from Firebase Firestore with React.js
Oct 6, 2022Limiting the Firebase Storage space used by each customerLimiting the amount of Storage space used by your customers can be tricky. In this article, we show how to set a quota for each of your customers.
Oct 6, 2022Creating a Waitlist with Firebase AuthImplement a waitlist sign-up with Firebase Auth and allow sign-ins in batches to your SaaS
Sep 29, 2022Using Firestore in Firebase Storage RulesFirebase Storage now allows you to use Firestore queries to in your security rules. Here is all you need to know!