MongoDB Map Reduce - MongoDB

What is the use of map reduce in MongoDB?

Based on the MongoDB documentation, Map-reduce is a data processing paradigm for compressing huge volumes of data into useful collective results. MongoDB makes use of mapReduce command for map-reduce operations. Basically, MapReduce is used for processing large data sets.

MapReduce Command

Below is the syntax for the basic mapReduce command

Map-reduce function will first query the collection and will then map the result documents to produce key-value pairs. Then this is reduced based on the keys which have multiple values.

In the above syntax

  • map is a javascript function which will map a value with a key and produces a key-value pair
  • reduce is a javascript function which will reduce or group all the documents which have the same key
  • out will specify the location of the map-reduce query result
  • query will specify the optional selection criteria for selecting documents
  • sort will specify the optional sort criteria
  • limit will specify the optional maximum number of documents to be returned

Using MapReduce

Consider below document structure storing user posts. Document will store user_name of the user and the status of post.

Now, let’s use a mapReduce function in our posts collection for selecting all the active posts, grouping them on the basis of user_name and then counting the number of posts by each user using below code

Above mapReduce query results in below output

Result shows that a total of 4 documents matched the query (status:"active"), map function emitted 4 documents with key-value pairs and finally reduce function grouped mapped documents having the same keys into 2.

To see the result of this mapReduce query, use find operator as shown below

Above query will give below result which indicates that both users tom and mark have two posts in active states

In a similar way, MapReduce queries are used for constructing large complex aggregation queries. Custom Javascript functions makes use of MapReduce which is very flexible and powerful.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

MongoDB Topics