Implementing MongoDB map-reduce


Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results.

Let us create a collection with documents −

> db.demo280.insertOne({"CustomerName":"Chris","isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e49116edd099650a5401a62")
}
> db.demo280.insertOne({"CustomerName":"Mike","isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e491170dd099650a5401a63")
}
> db.demo280.insertOne({"CustomerName":"David","isMarried":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e491170dd099650a5401a64")
}
> db.demo280.insertOne({"CustomerName":"Bob","isMarried":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e491171dd099650a5401a65")
}

Display all documents from a collection with the help of find() method −

> db.demo280.find();

This will produce the following output −

{ "_id" : ObjectId("5e49116edd099650a5401a62"), "CustomerName" : "Chris", "isMarried" : true }
{ "_id" : ObjectId("5e491170dd099650a5401a63"), "CustomerName" : "Mike", "isMarried" : false }
{ "_id" : ObjectId("5e491170dd099650a5401a64"), "CustomerName" : "David", "isMarried" : false }
{ "_id" : ObjectId("5e491171dd099650a5401a65"), "CustomerName" : "Bob", "isMarried" : true }

Following is the query to implement Mongo DB mapreduce −

> db.demo280.mapReduce(
...   function() { emit(this.isMarried,true); },
...
...   function(key, values) {return Array.sum(values)}, {
...      query:{isMarried:true},
...      out:"Output"
...   }
...)

This will produce the following output displaying total 2 documents (input: 2) matched the query and 2 results were emitted (emit: 2) −

{
   "result" : "Output",
   "timeMillis" : 1241,
   "counts" : {
      "input" : 2,
      "emit" : 2,
      "reduce" : 1,
      "output" : 1
   },
   "ok" : 1
}

Updated on: 31-Mar-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements