MongoDB\Collection::mapReduce()
Deprecated since version 1.12.
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( MongoDB\BSON\JavascriptInterface $map, MongoDB\BSON\JavascriptInterface $reduce, string|array|object $out, array $options = [] ): MongoDB\MapReduceResult
Parameters
$map
: MongoDB\BSON\JavascriptA 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\JavascriptA 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
: arrayAn array specifying the desired options.
NameTypeDescriptionbypassDocumentValidationbooleanIf
true
, allows the write operation to circumvent document level validation. Defaults tofalse
.This only applies when results are output to a collection.
collationarray|objectCollation 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.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.
commentmixedEnables 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.
finalizeFollows the reduce method and modifies the output.
Passing a Javascript instance with a scope is deprecated. Put all scope variables in the
scope
option of the MapReduce operation.jsModebooleanSpecifies whether to convert intermediate data into BSON format between the execution of the map and reduce functions.limitintegerSpecifies a maximum number of documents for the input into the map function.maxTimeMSintegerThe cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
queryarray|objectSpecifies the selection criteria using query operators for determining the documents input to the map function.readConcernRead 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.readPreferenceRead 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.
scopearray|objectSpecifies global variables that are accessible in the map, reduce, and finalize functions.sessionClient session to associate with the operation.
New in version 1.3.
sortarray|objectThe sort specification for the ordering of the results.typeMaparrayThe type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection's type map.
verbosebooleanSpecifies whether to include the timing information in the result information.writeConcernWrite 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.
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 extension 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.
$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