Learn About The MapReduce Command in MongoDB

MapReduce Command

MapReduce Command

In this article, we are going to discuss the utilization of the MapReduce Command in MongoDB. Map-reduce is a method in the MongoDB which is used as a data processing paradigm for condensing bulky volumes of data into valuable aggregated results. We can use mapReduce command in the MongoDB for map-reduce operations as well as processing of large data sets.

Basic MapReduce Command
The following is the syntax for the basic mapReduce command.

Explanation: –
The above map-reduce function will query the collection, and then map the output documents to the emit key-value pairs. After this, it is reduced based on the keys that have multiple values. Here, we have used the following functions and parameters.
• Map: – It is a JavaScript function. It is used to map a value with a key and produces a key-value pair.
• Reduce: – It is a JavaScript function. It is used to reduce or group together all the documents which have the same key.
• Out: – It is used to specify the location of the map-reduce query output.
• Query: – It is used to specify the optional selection criteria for selecting documents.
• Sort: – It is used to specify the optional sort criteria.
• Limit: – It is used to specify the optional maximum number of documents which are desired to be returned.

Example on used of MapReduce function
Consider the following document structure that stores book details author wise. The document stores author_name of the book author and the status of book.

Now, we are going to use the mapReduce function on our author collection in order to select all the active books, group them together on the basis of author_name and then count the number of books by each author by using the following code in MongoDB.

Explanation on above output
The result shows above is a total of 4 documents which are matched by the query (status:”active”), the map function has produced 4 documents with key-value pairs and finally the reduce function has grouped all the mapped documents which have the same keys into 1.
We can use the find operator in order to see the result of this mapReduce query by writing the following lines of code.

The MongoDB query will give the above result, which specifies the author name as “aparajita” who has 4 books in the active state.

In the same way, we can use MapReduce queries in order to construct huge complex aggregation queries. Also, we can use custom JavaScript functions along with the use of MapReduce function which together can provide more flexibility than traditional methods.

Conclusion: –
In this article, we discussed the utilization of the MapReduce Command in the MongoDB along with the suitable examples.


Please enter your comment!
Please enter your name here