=====================================
MongoDB\\Collection::countDocuments()
=====================================

.. versionadded:: 1.4

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\\Collection::countDocuments()

   Count the number of documents that match the filter criteria.

   .. code-block:: php

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

   This method has the following parameters:

   .. include:: /includes/apiargs/MongoDBCollection-method-countDocuments-param.rst

   The ``$options`` parameter supports the following options:

   .. include:: /includes/apiargs/MongoDBCollection-method-countDocuments-option.rst

Return Values
-------------

The number of documents matching the filter criteria.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Behavior
--------

Internally, this method uses the ``$group`` aggregation pipeline operator to
obtain the result. If a ``filter`` parameter is given, this is converted into
a ``$match`` pipeline operator. Optional ``$skip`` and ``$limit`` stages are
added between ``$match`` and ``group`` if present in the options.

Since this method uses an aggregation pipeline, some query operators accepted
within a :phpmethod:`MongoDB\\Collection::count()` ``filter`` cannot be used.
Consider the following alternatives to these restricted operators:

.. list-table::
   :header-rows: 1

   * - Restricted
     - Alternative Syntax

   * - :query:`$near`
     - :query:`$geoWithin` with :query:`$center`

   * - :query:`$nearSphere`
     - :query:`$geoWithin` with :query:`$centerSphere`

   * - :query:`$where`
     - :query:`$expr` (requires MongoDB 3.6+)

.. include:: /includes/extracts/note-bson-comparison.rst

.. todo: add output and examples

See Also
--------

- :phpmethod:`MongoDB\\Collection::estimatedDocumentCount()`
