Navigation

MongoDB\Collection::mapReduce()

New in version 1.2.

Definition

MongoDB\Collection::mapReduce

The mapReduce command allows you to run map-reduce aggregation operations over a collection.

function mapReduce($map, $reduce, $out, array $options = []): MongoDB\MapReduceResult

This method has the following parameters:

Parameter Type Description
$map MongoDB\BSON\Javascript A JavaScript function that associates or “maps” a value with a key and emits the key and value pair.
$reduce MongoDB\BSON\Javascript A JavaScript function that “reduces” to a single object all the values associated with a particular key.
$out string|document 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 Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
bypassDocumentValidation boolean

Optional. If true, allows the write operation to circumvent document level validation. Defaults to false.

This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation.

This only applies when results are output to a collection.

collation array|object

Optional. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

finalize MongoDB\BSON\Javascript Optional. Follows the reduce method and modifies the output.
jsMode boolean Optional. Specifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions. The default is false.
limit integer Optional. Specifies a maximum number of documents for the input into the map function.
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.
query document Optional. Specifies the selection criteria using query operators for determining the documents input to the map function.
readConcern MongoDB\Driver\ReadConcern

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

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

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.

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

scope document Optional. Specifies global variables that are accessible in the map, reduce, and finalize functions.
session MongoDB\Driver\Session

Optional. Client session to associate with the operation.

Sessions are not supported for server versions prior to 3.6.

New in version 1.3.

sort array|object Optional. The sort specification for the ordering of the results.
typeMap array Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection’s type map.
verbose boolean Optional. Specifies whether to include the timing information in the result information. The default is true.
writeConcern MongoDB\Driver\WriteConcern

Optional. Write concern to use for the operation. Defaults to the collection’s write concern.

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

Return Values

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

Errors/Exceptions

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\Exception\UnexpectedValueException if the command response from the server was malformed.

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

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 Map-Reduce and 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 BSON Document Size limit, which is currently 16 megabytes.

MongoDB supports map-reduce operations on sharded collections. Map-reduce operations can also output the results to a sharded collection. See Map-Reduce and Sharded Collections.

Example

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

<?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:

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

  • mapReduce command reference in the MongoDB manual
  • Map-Reduce documentation in the MongoDB manual