================================
MongoDB\\Collection::mapReduce()
================================

.. deprecated:: 1.12

.. versionadded:: 1.2

.. default-domain:: mongodb

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

Definition
----------

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

   The :manual:`mapReduce </reference/command/mapReduce>` command allows you to
   run map-reduce aggregation operations over a collection.

   .. code-block:: php

      function mapReduce(
          MongoDB\BSON\JavascriptInterface $map,
          MongoDB\BSON\JavascriptInterface $reduce,
          string|array|object $out,
          array $options = []
      ): MongoDB\MapReduceResult

Parameters
----------

``$map`` : :php:`MongoDB\BSON\Javascript <mongodb-bson-javascript>`
  A JavaScript function that associates or "maps" a value with a key and emits
  the key and value pair.

  .. note::

     Passing a Javascript instance with a scope is deprecated. Put all scope
     variables in the ``scope`` option of the MapReduce operation.

``$reduce`` : :php:`MongoDB\BSON\Javascript <class.mongodb-bson-javascript>`
  A JavaScript function that "reduces" to a single object all the values
  associated with a particular key.

  .. note::

     Passing a Javascript instance with a scope is deprecated. Put all scope
     variables in the ``scope`` option of the MapReduce operation.

``$out`` : string|array|object
  Specifies where to output the result of the map-reduce operation. You can
  either output to a collection or return the result inline. On a primary member
  of a replica set you can output either to a collection or inline, but on a
  secondary, only inline output is possible.

``$options`` : array
  An array specifying the desired options.

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - bypassDocumentValidation
       - boolean
       - If ``true``, allows the write operation to circumvent document level
         validation. Defaults to ``false``.

         This only applies when results are output to a collection.

     * - collation
       - array|object
       - .. include:: /includes/extracts/collection-option-collation.rst

     * - comment
       - mixed
       - .. include:: /includes/extracts/common-option-comment.rst

         .. include:: /includes/extracts/option-requires-4.4.rst

         .. versionadded:: 1.13

     * - finalize
       - :php:`MongoDB\BSON\Javascript <class.mongodb-bson-javascript>`
       - Follows the reduce method and modifies the output.

         .. note::

            Passing a Javascript instance with a scope is deprecated. Put all
            scope variables in the ``scope`` option of the MapReduce operation.

     * - jsMode
       - boolean
       - Specifies whether to convert intermediate data into BSON format between
         the execution of the map and reduce functions.

     * - limit
       - integer
       - Specifies a maximum number of documents for the input into the map
         function.

     * - maxTimeMS
       - integer
       - .. include:: /includes/extracts/common-option-maxTimeMS.rst

     * - query
       - array|object
       - Specifies the selection criteria using query operators for determining
         the documents input to the map function.

     * - readConcern
       - :php:`MongoDB\Driver\ReadConcern <class.mongodb-driver-readconcern>`
       - .. include:: /includes/extracts/collection-option-readConcern.rst

         .. include:: /includes/extracts/common-option-readConcern-transaction.rst

     * - readPreference
       - :php:`MongoDB\Driver\ReadPreference <class.mongodb-driver-readpreference>`
       - .. include:: /includes/extracts/collection-option-readPreference.rst

         This option will be ignored when results are output to a collection.

     * - scope
       - array|object
       - Specifies global variables that are accessible in the map, reduce, and
         finalize functions.

     * - session
       - :php:`MongoDB\Driver\Session <class.mongodb-driver-session>`
       - .. include:: /includes/extracts/common-option-session.rst

         .. versionadded:: 1.3

     * - sort
       - array|object
       - The sort specification for the ordering of the results.

     * - typeMap
       - array
       - .. include:: /includes/extracts/collection-option-typeMap.rst

     * - verbose
       - boolean
       - Specifies whether to include the timing information in the result
         information.

     * - writeConcern
       - :php:`MongoDB\Driver\WriteConcern <class.mongodb-driver-writeconcern>`
       - .. include:: /includes/extracts/collection-option-writeConcern.rst

         .. include:: /includes/extracts/common-option-writeConcern-transaction.rst

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

A :phpclass:`MongoDB\MapReduceResult` object, which allows for iteration of
map-reduce results irrespective of the output method (e.g. inline, collection)
via the :php:`IteratorAggregate <iteratoraggregate>` interface. It also
provides access to command statistics.

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

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

Behavior
--------

In MongoDB, the map-reduce operation can write results to a collection
or return the results inline. If you write map-reduce output to a
collection, you can perform subsequent map-reduce operations on the
same input collection that merge replace, merge, or reduce new results
with previous results. See :manual:`Map-Reduce </core/map-reduce>` and
:manual:`Perform Incremental Map-Reduce </tutorial/perform-incremental-map-reduce>`
for details and examples.

When returning the results of a map-reduce operation *inline*, the
result documents must be within the :limit:`BSON Document Size` limit,
which is currently 16 megabytes.

MongoDB supports map-reduce operations on :manual:`sharded collections
</sharding>`. Map-reduce operations can also output
the results to a sharded collection. See
:manual:`Map-Reduce and Sharded Collections </core/map-reduce-sharded-collections>`.

Example
-------

This example will use city populations to calculate the overall population of
each state.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->zips;

   $map = new MongoDB\BSON\Javascript('function() { emit(this.state, this.pop); }');
   $reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values) }');
   $out = ['inline' => 1];

   $populations = $collection->mapReduce($map, $reduce, $out);

   foreach ($populations as $pop) {
      var_dump($pop);
   };

The output would then resemble:

.. code-block:: none

   object(stdClass)#2293 (2) {
      ["_id"]=>
      string(2) "AK"
      ["value"]=>
      float(544698)
   }
   object(stdClass)#2300 (2) {
      ["_id"]=>
      string(2) "AL"
      ["value"]=>
      float(4040587)
   }
   object(stdClass)#2293 (2) {
      ["_id"]=>
      string(2) "AR"
      ["value"]=>
      float(2350725)
   }
   object(stdClass)#2300 (2) {
      ["_id"]=>
      string(2) "AZ"
      ["value"]=>
      float(3665228)
   }

See Also
--------

- :manual:`mapReduce </reference/command/mapReduce>` command reference in the MongoDB
  manual
- :manual:`Map-Reduce </core/map-reduce>` documentation in the MongoDB manual

