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:

db.CollectionName.stats().count

Hi

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.

2 Likes

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.

Regards,
Stennie

3 Likes

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