MongoDB Count() Method (original) (raw)

Last Updated : 5 May, 2026

The count() method improve was used to return the number of documents matching a query, but it is now deprecated in MongoDB.

Features of count() Method

Here are some features:

Syntax of count() Method

The count() method can be used in two ways:

1. Count all documents in a collection:

db.Collection_Name.count()

2. Count documents that match a filter condition:

db.collectionName.count(
selectionCriteria,
{
limit: ,
skip: ,
hint: ,
maxTimeMS: ,
readConcern: ,
collation:
}
)

**Selection Criteria:

**Optional Parameters:

The second parameter is an optional document that allows fine-tuning of the counting process.

**Return Type: The count() method returns an integer representing the number of documents that match the selection criteria.

Examples of Using count() in MongoDB

The collection contains multiple documents, each representing a student with name and age fields. Below is a sample dataset used for the examples:

Screenshot-2026-02-17-122212

Example 1: Count all Documents in a Collection

Count the total number of documents present in the student collection.

db.student.count()

**Output:

Screenshot-2026-02-17-122409

**Note: The db.collection.count() method is deprecated in MongoDB. Use db.collection.countDocuments() for accurate counts with filters, or db.collection.estimatedDocumentCount() for fast approximate counts of all documents.

Example 2: Count all Documents that Match a Query

Count documents in the student collection that meet a specific condition, such as age greater than 18.

db.student.count({age:{$gt:18}})

**Output:

Screenshot-2026-02-17-122633

Example 3: Count with limit and skip Parameters

Limit the number of documents counted while skipping a specified number of documents in the student collection.

db.student.count({}, { skip: 1, limit: 2 })

**Output:

Screenshot-2026-02-17-122824

Best Practices for Using count() in MongoDB

Here are some best practices :

1. Avoid Using count() in Transactions

Use a transaction-safe alternative for counting.

2. Use countDocuments() Instead of count()

Prefer the recommended method for accurate results.

3. Optimize Performance Using Indexes

Leverage indexes to speed up count queries.