MongoDB query to display alternative documents with mapReduce() function and emit even field values


Let us create a collection with documents −

> db.demo636.insert({id:1});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:2});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:3});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:4});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:5});
WriteResult({ "nInserted" : 1 })
> db.demo636.insert({id:6});
WriteResult({ "nInserted" : 1 })

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

> db.demo636.find();

This will produce the following output −

{ "_id" : ObjectId("5e9c127b6c954c74be91e6d2"), "id" : 1 }
{ "_id" : ObjectId("5e9c127e6c954c74be91e6d3"), "id" : 2 }
{ "_id" : ObjectId("5e9c127f6c954c74be91e6d4"), "id" : 3 }
{ "_id" : ObjectId("5e9c12816c954c74be91e6d5"), "id" : 4 }
{ "_id" : ObjectId("5e9c12836c954c74be91e6d6"), "id" : 5 }
{ "_id" : ObjectId("5e9c12896c954c74be91e6d7"), "id" : 6 }

Following is the query to implement mapReduce() and display only the even values −

> db.demo636.mapReduce(
...    function () {
...       oddCounter++;
...       var id= this._id;
...       delete this._id;
...       if ( oddCounter % d != 0 )
...       emit(id, this );
...    },
...    function() {},
...    {
...       "scope": { "oddCounter": 0, "d": 2 },
...       "out": { "inline": 1 }
...    }
... )

This will produce the following output −

{
   "results" : [
      {
         "_id" : ObjectId("5e9c127b6c954c74be91e6d2"),
         "value" : {
            "id" : 1
      }
   },
   {
      "_id" : ObjectId("5e9c127f6c954c74be91e6d4"),
      "value" : {
         "id" : 3
      }
   },
   {
      "_id" : ObjectId("5e9c12836c954c74be91e6d6"),
      "value" : {
         "id" : 5
      }
   }
],
"timeMillis" : 29,
"counts" : {
   "input" : 6,
   "emit" : 3,
   "reduce" : 0,
   "output" : 3
   },
"ok" : 1
}

Updated on: 12-May-2020

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements