Docs Menu

Docs HomePHP Library Manual

MongoDB\Collection::mapReduce()

On this page

  • Definition
  • Parameters
  • Return Values
  • Errors/Exceptions
  • Behavior
  • Example
  • See Also

Deprecated since version 1.12.

New in version 1.2.

MongoDB\Collection::mapReduce()

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

function mapReduce(
MongoDB\BSON\JavascriptInterface $map,
MongoDB\BSON\JavascriptInterface $reduce,
string|array|object $out,
array $options = []
): MongoDB\MapReduceResult
$map : 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 : 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.

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
comment
mixed

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

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

New in version 1.13.

finalize

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

The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

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

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.

readPreference

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
array|object
Specifies global variables that are accessible in the map, reduce, and finalize functions.
session

Client session to associate with the operation.

New in version 1.3.

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

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
Specifies whether to include the timing information in the result information.
writeConcern

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.

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.

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).

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.

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)
}
  • mapReduce command reference in the MongoDB manual

  • Map-Reduce documentation in the MongoDB manual

←  MongoDB\Collection::listSearchIndexes()MongoDB\Collection::rename() →