MongoDB Map Reduce example using Mongo Shell and Java Driver

Map Reduce is a data processing technique that condenses large volumes of data into aggregated results. MongoDB mapreduce command is provided to accomplish this task.

Lets consider the following examples that demonstrates the mapreduce command usage.

Consider the car collection which contains the following documents;

Now let’s write the map reduce function on car collection grouping by speed and categorizing them as overspeed cars.

Define the map function as shown below

This function categorizes the car as overspeed cars based on the speed. Here “this” refers to the current document for which map reducing has to be processed.

Define the reduce function with arguments key and values to caluclate the average speed of the overspeed car as

Here the speed is summed up for all the cars through iterating the loop and the average speed is calculated as the sum of all the speed by the number of overspeed cars.

Invoke the map reduce function by calling the Map and Reduce functions on all the documents present in the car collection as;

The output is fetched in a collection avgspeed.If this collection does not exist a new collection is created else the new contents are replaced.

To see the documents invoke db.avgspeed.find()


The output states that there average speed of the overspeed cars is 85.

MongoDB Map Reduce Java Example

Below is the java program for above mongo shell example, note that it’s just showcasing the Map Reduce functions working. So make sure data is present in the collection for it to give desired result.

Above java program produces following output.

That’s all for a brief overview of Map Reduce functions in the MongoDB database, we will look other MongoDB features in coming posts.

By admin

Leave a Reply

%d bloggers like this: