==============================
MongoDB\\Database::aggregate()
==============================

.. versionadded:: 1.5

.. default-domain:: mongodb

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

Definition
----------

.. phpmethod:: MongoDB\\Database::aggregate()

   Runs a specified :manual:`admin/diagnostic pipeline
   </reference/operator/aggregation-pipeline/#db-aggregate-stages>` which does
   not require an underlying collection. For aggregations on collection data,
   see :phpmethod:`MongoDB\\Collection::aggregate()`.

   .. code-block:: php

      function aggregate(array $pipeline, array $options = []): Traversable

   This method has the following parameters:

   .. include:: /includes/apiargs/MongoDBDatabase-method-aggregate-param.rst

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

   .. include:: /includes/apiargs/MongoDBDatabase-method-aggregate-option.rst

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

A :php:`MongoDB\\Driver\\Cursor <class.mongodb-driver-cursor>` or
:php:`ArrayIterator <arrayiterator>` object. In both cases, the return value
will be :php:`Traversable <traversable>`.

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

.. _php-db-agg-method-behavior:

Examples
--------

The following aggregation example lists all running commands using the
``$currentOp`` aggregation pipeline stage, then filters this list to only show
running command operations.

.. code-block:: php

   <?php

   $database = (new MongoDB\Client)->admin;

   $cursor = $database->aggregate(
       [
           ['$currentOp' => []],
           ['$match' => ['op' => 'command'],
       ]
   );

See Also
--------

- :phpmethod:`MongoDB\\Collection::aggregate()`
- :manual:`aggregate </reference/command/aggregate>` command reference in the
  MongoDB manual
- :manual:`Aggregation Pipeline </core/aggregation-pipeline>` documentation in
  the MongoDB Manual
