Visit complete MongoDB roadmap

← Back to Topics List

Counting Documents

When working with MongoDB, you might often need to know the number of documents present in a collection. MongoDB provides a few methods to efficiently count documents in a collection. In this section, we will discuss the following methods:

  • countDocuments()
  • estimatedDocumentCount()


The countDocuments() method is used to count the number of documents in a collection based on a specified filter. It provides an accurate count that may involve reading all documents in the collection.


collection.countDocuments(filter, options);
  • filter: (Optional) A query that will filter the documents before the count is applied.
  • options: (Optional) Additional options for the count operation such as skip, limit, and collation.


  { status: 'completed' },
  (err, count) => {
    console.log('Number of completed orders: ', count);

In the example above, we count the number of documents in the orders collection that have astatus field equal to 'completed'.


The estimatedDocumentCount() method provides an approximate count of documents in the collection, without applying any filters. This method uses the collection’s metadata to determine the count and is generally faster than countDocuments().


  • options: (Optional) Additional options for the count operation such as maxTimeMS.


db.collection('orders').estimatedDocumentCount((err, count) => {
  console.log('Estimated number of orders: ', count);

In the example above, we get the estimated number of documents in the orders collection.

Keep in mind that you should use the countDocuments() method when you need to apply filters to count documents, while estimatedDocumentCount() should be used when an approximate count is sufficient and you don’t need to apply any filters.

Community is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Roadmaps Best Practices Guides Videos Store YouTube by Kamran Ahmed

Community created roadmaps, articles, resources and journeys to help you choose your path and grow in your career.

© · FAQs · Terms · Privacy


The leading DevOps resource for Kubernetes, cloud-native computing, and the latest in at-scale development, deployment, and management.