MongoDB Map Reduce

In this MongoDB TutorialMongoDB Map Reduce, we shall learn to use mapReduce() function for performing aggregation operations on a MongoDB Collection, with the help of examples.

Syntax of Mongo mapReduce()

Following is the syntax of mapReduce() function that could be used in Mongo Shell

 

Example for MongoDB mapReduce()

In this example we shall take school db in which students is a collection and the collection has documents where each document has name of the student, marks he/she scored in a particular subject. We shall apply mapReduce function to accumulate the marks for each student.

Following is the students collection.

 

mapReduce() In Mongo Shell

Following is a step by step guide to prepare mapReduce function for the use case in Mongo Shell :

  1. Prepare Map function.

    Our map function should emit key-value pair. And in this case, name is key and value is marks.

  2. Prepare Reduce function.

    Our map function should emit key-value pair. And in this case, name is key and value is marks.

     

  3. Prepare mapReduce function.

    Our map function should emit key-value pair. And in this case, name is key and value is marks.

    out: "totals"  : the output is written to totals collection in the same database.

  4. Start Mongo Daemon.

    Run the following command in terminal to start mongo daemon.

    Now Mongo Daemon would be waiting for connections on port 27017.

  5. Run mapReduce.

    Start a Mongo Shell and Run the above commands (in Step 1 to Step 3) in Mongo Shell.

    The value has been accumulated (aggregated) for the key values and the output is written to totals collection.

 

Using mapReduce Command in Mongo Script

Following is the Mongo Script file that runs mapReduce command and writes result to totals collection

Run the JavaScript file using mongo command

You may check the totals collection

 

You may choose any property as a key or value from the collection for the mapReduce() function.

 

Conclusion

We have learnt how to use MongoDB MapReduce function in Mongo Shell and Mongo Script with examples.