Mongo Query Total number of records : count

We have a requirement to get the total number of records from web application. We are using the mongo DB count function to get the total records count from collection.

Problem: we have millions of records in a collections and the count function is not performant efficient to get the result.

What is the quickest way or alternative soultion to get the total number of records in a collection through mongo query ?

there are a few count method:

count and countdocuments and estimatedDocumentCount.

you can check which can meet your requirements.

But another way is to maintain a total number of docs on your own, which may still be inconsistent sometimes. (can happen without using a transaction).

1 Like