Beginners Guide to MongoDB Map-Reduce

As per MongoDB documentation, “Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results”. For beginners this is a bit complex to understand. So I tried to explain it in detail.
Let’s first take an example from our very own RDBMS:
Suppose an organization only hires contract employees on weekly basis. And they maintain a grade also. Let’s say they maintain a table which have below data:

Employee ID Grade Salary Week
1 A 20 1
2 A 25 1
3 B 15 1
2 A 25            2
1 A 20 2

Now to get the expenses spend for grade A in two weeks should be something like this:

This is so easy in RDBMS. But in MongoDB as we know the columns are not fixed. And it uses BSON file to store data. So there is no easy way to get the aggregated results from a large set of records.

To solve this MongoDB introduced Map-Reduce.

I have taken the example from MongoDB official documentation and tried to explain in detail below.

Suppose there is a Collection ‘Orders’ which have four documents.

 

Now we want to get the total amount of documents with status:”A” and group by cust_id.

The output will be:

 

Now let’s take a detailed look what it’s actually doing:

In this command

emit (this.cust_id, ths.amount)
we are asking mongo to display cust_id and amount. It will return an array of values. Then in
return Array.sum(values)
command, we are asking mongo to reduce the value by doing a sum of all array elements.

In the line

Query: {status: “A”}
we are taking only those records which have status = A

At last in the Out statement we are specifying the output location. It can be a collection or inline. In the above case the output location is a collection named “order_totals”.

So this is the basic of Map-Reduce in MongoDB. For any questions please leave a comment.

Arijit Naskar

Arijit Naskar is a Software Developer and QA, also founder of alltechstories.com a popular tech tutorial & how-to website since 2014. He loves to explore new technologies and writing blogs.

You may also like...