On this page
This page documents a
mongoshmethod. This is not the documentation for database commands or language-specific drivers, such as Node.js.
For the database command, see the
countfield returned by the
For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongoshell documentation, refer to the documentation for the corresponding MongoDB Server release:
Returns the count of all documents in a collection or view.
db.collection.estimatedDocumentCount( <options> )ParameterTypeDescriptionoptionsdocumentOptional. Extra options that affect the count behavior.
optionsdocument can contain the following:FieldTypeDescription
maxTimeMSintegerOptional. The maximum amount of time to allow the count to run.
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.
On a sharded cluster, the resulting count will not correctly filter out orphaned documents.
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
--syncdelay settings may have more or less frequent
validate on each collection on the
to restore statistics after an unclean shutdown.
After an unclean shutdown:
Starting in MongoDB 4.2, if the client that issued
disconnects before the operation completes, MongoDB marks
for termination using
Count and Transactions
When you use
db.collection.estimatedDocumentCount() in a transaction, the resulting count will
not filter out any uncommitted multi-document transactions.
The following example uses
db.collection.estimatedDocumentCount() to retrieve the count of
all documents in the