0
0
MongodbHow-ToBeginner · 3 min read

How to Count Documents in MongoDB: Syntax and Examples

To count documents in MongoDB, use the countDocuments() method on a collection. This method returns the number of documents matching a query filter or all documents if no filter is provided.
📐

Syntax

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

  • filter: An optional object to specify criteria for matching documents.
  • options: Optional settings like limit or skip.

Example syntax:

db.collection.countDocuments(filter, options)
mongodb
db.collection.countDocuments({ age: { $gt: 25 } })
💻

Example

This example counts how many users are older than 25 in the users collection.

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

async function countUsers() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const database = client.db('testdb');
    const users = database.collection('users');

    const count = await users.countDocuments({ age: { $gt: 25 } });
    console.log('Number of users older than 25:', count);
  } finally {
    await client.close();
  }
}

countUsers();
Output
Number of users older than 25: 42
⚠️

Common Pitfalls

Common mistakes when counting documents include:

  • Using count() instead of countDocuments(), which is deprecated and less accurate.
  • Not providing a filter when you want to count specific documents.
  • Confusing estimatedDocumentCount() with countDocuments(); the former is faster but less precise.
mongodb
/* Wrong: deprecated count() method */
db.users.count({ age: { $gt: 25 } });

/* Right: use countDocuments() */
db.users.countDocuments({ age: { $gt: 25 } });
📊

Quick Reference

MethodDescriptionUse Case
countDocuments(filter)Counts documents matching filterAccurate count with query
estimatedDocumentCount()Estimates total documents quicklyFast count without filter
count()Deprecated methodAvoid using

Key Takeaways

Use countDocuments() to count documents matching a filter in MongoDB.
Avoid the deprecated count() method for counting documents.
estimatedDocumentCount() is faster but less precise and does not accept filters.
Always provide a filter to countDocuments() when you want specific counts.
countDocuments() returns a promise in modern drivers, so use async/await or callbacks.