Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /

Map-Reduce

Note

Aggregation Pipeline as Alternative

Starting in MongoDB 5.0, map-reduce is deprecated:

For examples of aggregation pipeline alternatives to map-reduce, see:

You can run aggregation pipelines in the UI for deployments hosted in MongoDB Atlas.

Map-reduce is a data processing paradigm for condensing large volumes of data into aggregated results. To perform map-reduce operations, MongoDB provides the mapReduce database command.

Consider the following map-reduce operation:

Diagram of the annotated map-reduce operation.

MongoDB applies the map phase to each input document (the documents in the collection that match the query condition). The map function emits key-value pairs. For keys that have multiple values, MongoDB applies the reduce phase, which collects and condenses the data, and then stores the results in a collection. The output of the reduce function can optionally pass through a finalize function to further process the results.

All map-reduce functions in MongoDB are JavaScript and run within the mongod process. Map-reduce operations take a single collection as input and can apply sorting and limiting before the map stage. mapReduce can return results as a document or write them to a collection.

Note

Map-reduce is unsupported for MongoDB Atlas Free and Flex clusters.

Map-reduce operations use custom JavaScript functions to map values to a key. If a key has multiple values, the operation reduces them to a single object. A map function can emit multiple key-value pairs or none. An optional finalize function can make further modifications to the results.

A map-reduce operation can write results to a collection or return them inline. If you write results to a collection, you can run subsequent map-reduce operations against the same input collection that replace, merge, or reduce new results with previous results. See mapReduce and Perform Incremental Map-Reduce for examples.

When returning results inline, the result documents must fit within the BSON Document Size limit of 16 mebibytes. For more limits and restrictions, see mapReduce.

MongoDB supports map-reduce operations on sharded collections.

Views do not support map-reduce operations.

Back

SQL to Aggregation

On this page