RefirebaseRefirebase

count

Count documents in a Firestore collection efficiently.

Overview

The count method uses Firestore's server-side aggregation feature to count documents matching optional filters without actually retrieving the document data. This makes it highly efficient and cost-effective compared to traditional client-side counting.

Counting documents
import { db } from 'refirebase';

// Count all documents in the 'users' collection
const totalUsers = await db.firestore.count('users');

// Count active users with filters
const activeUsers = await db.firestore.count('users', {
  where: { active: true }
});

if (typeof activeUsers === 'number') {
  console.log(`There are ${activeUsers} active users.`);
} else {
  console.error(activeUsers.error);
}

Parameters

ParamTypeDescription
collectionName*stringThe name of the Firestore collection.
optionsGetByCondition<T>Optional query filters, such as where clauses.

Return value

Returns

Promise<number | FirestoreError>

Returns the number of documents matching the query, or a FirestoreError object if an error occurs.