Getting count of documents in large collection

I need to get the exact number of documents in a collection containing about15 million documents. But on using count( ) method, the output is either timing out or is buffering for a very long time.

How can I get this count?

What is the total size in Mb is your collection?

What is your system configuration, RAM, disks, …?

You may try:

db.find().projection( { _id : 1 } ).count()

An alternative way to find the number of documents, if you do not have any query is using:



I’m having trouble counting all 25 million documents.
It takes about 12.50 seconds.
Use about 54% CPU.

Can you make it better or use minimal CPU and Ram?

Hello @klingofmonsterdev, and welcome to the MongoDB Community forums! :wave:

Are you trying to get a count of all documents in your collection? If so, did you try Steeve’s suggestion of running db.collectionName.stats().count? This should use metadata information on the collection without running any query against it.


Welcome to the MongoDB community @klingofmonsterdev !

FYI, the collection.stats() metadata count is the same as the estimatedDocumentCount() in MongoDB driver and shell APIs. You can use this if speed is more important than accuracy for your use case.



Thanks for the good advice.
Now I use db.collection.estimatedDocumentCount().
But if I want to find query What’s the best way?