db.collection.estimatedDocumentCount()
On this page
MongoDB with drivers
This page documents a mongosh
method. To see the equivalent
method in a MongoDB driver, see the corresponding page for your
programming language:
Definition
db.collection.estimatedDocumentCount(options)
Returns the count of all documents in a collection or view.
db.collection.estimatedDocumentCount( <options> ) ParameterTypeDescriptionoptions
document
Optional. Extra options that affect the count behavior.
The
options
document can contain the following:FieldTypeDescriptionmaxTimeMS
integer
Optional. The maximum amount of time to allow the count to run.
Compatibility
This method is available in deployments hosted in the following environments:
MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Behavior
Mechanics
db.collection.estimatedDocumentCount()
does not take a query
filter and instead uses metadata to return the count for a collection.
For a view:
There is no metadata.
The document count is calculated by executing the aggregation pipeline in the view definition.
There is no fast estimated document count.
Sharded Clusters
On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
Unclean Shutdown
This section only applies to collections.
After an unclean shutdown, the count may be incorrect.
After an unclean shutdown of a mongod
using the Wired Tiger storage engine, count statistics reported by
db.collection.estimatedDocumentCount()
may be inaccurate.
The amount of drift depends on the number of insert, update, or delete
operations performed between the last checkpoint and the unclean shutdown. Checkpoints
usually occur every 60 seconds. However, mongod
instances running
with non-default --syncdelay
settings may have more or less frequent
checkpoints.
Run validate
on each collection on the mongod
to restore statistics after an unclean shutdown.
After an unclean shutdown:
Client Disconnection
Starting in MongoDB 4.2, if the client that issued db.collection.estimatedDocumentCount()
disconnects before the operation completes, MongoDB marks db.collection.estimatedDocumentCount()
for termination using killOp
.
Count and Transactions
When you use db.collection.estimatedDocumentCount()
in a transaction, the resulting count will
not filter out any uncommitted multi-document transactions.
Example
The following example uses
db.collection.estimatedDocumentCount()
to retrieve the count of
all documents in the orders
collection:
db.orders.estimatedDocumentCount({})