MongoDB Aggregate Second Element from Input Element?


To aggregate second element from input element, use mapReduce(). 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.demo621.insert({ _id: 101, Name1: "John", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 102, Name1: "Bob", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 103, Name1: "Chris", Name2: "John" });
WriteResult({ "nInserted" : 1 })
> db.demo621.insert({ _id: 104, Name1: "Sam", Name2: "John" });
WriteResult({ "nInserted" : 1 })

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

> db.demo621.find();

This will produce the following output −

{ "_id" : 101, "Name1" : "John", "Name2" : "John" }
{ "_id" : 102, "Name1" : "Bob", "Name2" : "John" }
{ "_id" : 103, "Name1" : "Chris", "Name2" : "John" }
{ "_id" : 104, "Name1" : "Sam", "Name2" : "John" }

Following is the query to aggregate second element from input element −

> db.demo621.mapReduce(
...    function () {
...       track++;
...       var actualId= this._id;
...       delete this._id;
...       if ( track % div == 0 )
...       emit(actualId, this );
...    },
...    function() {},
...    {
...       "scope": { "track": 0, "div": 2 },
...       "out": { "inline": 1 }
...    }
... )

This will produce the following output −

{
   "results" : [
      {
         "_id" : 102,
         "value" : {
            "Name1" : "Bob",
            "Name2" : "John"
         }
      },
   {
      "_id" : 104,
      "value" : {
         "Name1" : "Sam",
         "Name2" : "John"
      }
   }
],
"timeMillis" : 48,
"counts" : {
   "input" : 4,
   "emit" : 2,
   "reduce" : 0,
   "output" : 2
},
"ok" : 1
}

Updated on: 12-May-2020

63 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements