In MongoDB the db.collection.estimatedDocumentCount()
method returns the count of all documents in a collection or view.
The collection
part is the name of the collection or view to perform the count operation on.
The db.collection.estimatedDocumentCount()
method wraps the count
command.
Example
Suppose we have a collection called pets
with the following documents:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 } { "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 } { "_id" : 3, "name" : "Meow", "type" : "Cat", "weight" : 7 } { "_id" : 4, "name" : "Scratch", "type" : "Cat", "weight" : 8 } { "_id" : 5, "name" : "Bruce", "type" : "Bat", "weight" : 3 } { "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 } { "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }
We can use the following query to return the number of documents in the collection:
db.pets.estimatedDocumentCount()
Result:
7
The db.collection.estimatedDocumentCount()
method doesn’t take a query filter. It instead uses metadata to return the document count for the whole collection.
However, it still works when provided with an empty document.
db.pets.estimatedDocumentCount({})
Result:
7
The maxTimeMS
Parameter
The db.collection.estimatedDocumentCount()
method accepts just one (optional) parameter: the maxTimeMS
parameter. This allows you to set the maximum amount of time that the count operation can run.
Example:
db.pets.estimatedDocumentCount({}, { maxTimeMS: 5000 })
Result:
7
Deprecation of count()
in Favour of estimatedDocumentCount()
Note that the MongoDB documentation states the following:
MongoDB drivers compatible with the 4.0 features deprecate their respective cursor and collection
count()
APIs in favor of new APIs forcountDocuments()
andestimatedDocumentCount()
. For the specific API names for a given driver, see the driver documentation.
More Information
On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
Also, after an unclean shutdown, the count may be incorrect.
See the MongoDB documentation for more information.