db.collection.estimatedDocumentCount()

Definition

  • db.collection.estimatedDocumentCount(options)

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

New in version 4.0.3.

Returns the count of all documents in a collection or view. Themethod wraps the count command.

  1. db.collection.estimatedDocumentCount( <options> )

ParameterTypeDescriptionoptionsdocumentOptional. Extra options that affect the count behavior.

The options document can contain the following:

FieldTypeDescriptionmaxTimeMSintegerOptional. The maximum amount of time to allow the count to run.

Behavior

Mechanics

db.collection.estimatedDocumentCount() does not take a queryfilter and instead uses metadata to return the count for a collection.

Sharded Clusters

On a sharded cluster, the resulting count will not correctly filter outorphaned documents.

Unclean Shutdown

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 bydb.collection.estimatedDocumentCount() may be inaccurate.

The amount of drift depends on the number of insert, update, or deleteoperations performed between the last checkpoint and the unclean shutdown. Checkpointsusually occur every 60 seconds. However, mongod instances runningwith non-default —syncdelay settings may have more or less frequentcheckpoints.

Run validate on each collection on the mongodto restore the correct statistics after an unclean shutdown.

Client Disconnection

Starting in MongoDB 4.2, if the client that issued the db.collection.estimatedDocumentCount()disconnects before the operation completes, MongoDB marksthe db.collection.estimatedDocumentCount() for termination (i.e. killOp on theoperation).

Example

The following example usesdb.collection.estimatedDocumentCount to retrieve the count ofall documents in the orders collection:

  1. db.orders.estimatedDocumentCount({})

See also