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.