Navigation

MongoDB\Collection::estimatedDocumentCount()

New in version 1.4.

Definition

MongoDB\Collection::estimatedDocumentCount

Gets an estimated number of documents in the collection using collection metadata.

function countDocuments(array $options = []): integer

This method has the following parameters:

Parameter Type Description
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
comment mixed

Optional. Enables users to specify an arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.

This is not supported for server versions prior to 4.4 and will result in an exception at execution time if used.

New in version 1.13.

maxTimeMS integer Optional. The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
readConcern MongoDB\Driver\ReadConcern

Optional. Read concern to use for the operation. Defaults to the collection’s read concern.

It is not possible to specify a read concern for individual operations as part of a transaction. Instead, set the readConcern option when starting the transaction with startTransaction.

readPreference MongoDB\Driver\ReadPreference Optional. Read preference to use for the operation. Defaults to the collection’s read preference.
session MongoDB\Driver\Session Optional. Client session to associate with the operation.

Return Values

An estimated number of documents in the collection.

Errors/Exceptions

MongoDB\Exception\UnexpectedValueException if the command response from the server was malformed.

MongoDB\Exception\UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Behavior

This method returns an estimate of the count of documents in the collection using collection metadata, rather than counting the documents or consulting an index. This method does not take a session option and cannot be executed within a transaction. See Count: Behavior in the MongoDB manual for more information.

This method is implemented using the count command. Due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command was not included in version “1” of the Stable API. Applications using this method with the Stable API are recommended to upgrade their server version to 5.0.9+ or disable strict mode to avoid encountering errors.

See Also