0
0
MongodbHow-ToBeginner · 3 min read

How to Use countDocuments in MongoDB: Syntax and Examples

Use countDocuments() in MongoDB to count the number of documents matching a query filter. It returns the count as a number and supports optional filters to count specific documents.
📐

Syntax

The countDocuments() method counts documents in a collection that match a given filter.

  • filter: An object specifying criteria to match documents (optional).
  • options: Additional options like limit or skip (optional).
mongodb
db.collection.countDocuments(filter, options)
💻

Example

This example shows how to count all documents and how to count documents with a filter in a MongoDB collection named users.

javascript
const { MongoClient } = require('mongodb');

async function run() {
  const client = new MongoClient('mongodb://localhost:27017');
  try {
    await client.connect();
    const db = client.db('testdb');
    const users = db.collection('users');

    // Count all documents
    const totalUsers = await users.countDocuments();
    console.log('Total users:', totalUsers);

    // Count users with age greater than 25
    const usersOver25 = await users.countDocuments({ age: { $gt: 25 } });
    console.log('Users over 25:', usersOver25);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Total users: 100 Users over 25: 40
⚠️

Common Pitfalls

Common mistakes when using countDocuments() include:

  • Using count() instead, which is deprecated and less accurate.
  • Not awaiting the promise in async code, causing unexpected results.
  • Passing an invalid filter object, which returns 0 instead of an error.
mongodb
/* Wrong: Using deprecated count() */
db.collection.count({ age: { $gt: 25 } });

/* Right: Use countDocuments() */
await db.collection.countDocuments({ age: { $gt: 25 } });
📊

Quick Reference

MethodDescription
countDocuments(filter, options)Counts documents matching the filter.
estimatedDocumentCount()Counts all documents without a filter (faster but less precise).
count()Legacy method, avoid using.

Key Takeaways

Use countDocuments() to get an accurate count of documents matching a filter.
Always await countDocuments() in async code to get the correct result.
Avoid using the deprecated count() method.
You can pass an empty filter to count all documents.
Use EstimatedDocumentCount() for a faster approximate count without filters.