2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Perform mapreduce over the field type array

We are implementing mapreducing on our application which contain millions of records. And the problem with the implementation is,e.g A documents as like below structure with the name as PRODUCT_WAREHOUSE which contains uncountable documents.

{    

    "PRODUCT_ID" : ObjectId("574c2f3497d3380a6c077927"),    

    "PRODUCT_NAME" : "XXX",    

    "SUB_PRODUCT_DETAILS" :

         [       

            {            "PRODUCT_ID" : "X",            

                         "PRODUCT_NAMES" : "XXX"     

             },        

            {         

                     "PRODUCT_ID" : "X",          

                     "PRODUCT_NAMES" : "XXX"       

            }   

       ], 

     "PRODUCT_LIKE_BY" : [        "XXX",         "XXX",...    ],

    ...

}

Now the question is when ever we perform any operation with individual field like PRODUCT_NAME then we got the exact result. But when ever we are going to perform any map-reduce operation with the field like SUB_PRODUCT_DETAILS or PRODUCT_LIKE_BY getting stuck. So need some sample snippet to achieve map-reduce over array type too.

userimage

Please find the below snippet which is a simple and easiest way to perform map-reduce on an Array types of fields with MongoDB nosql database.


var map = function(){

    for(var i=0;i<this.PRODUCT_LIKE_BY.length;i++){

        var key = this.PRODUCT_LIKE_BY[i];

        emit(key,1);

    }

}


var reduce = function(key,value){

      var res = 0;

      value.forEach(function(value){

            res +=1;

       });

    return res;

}


db.product_warehouse.mapReduce(map,reduce,{out:"result"});


And once you execute the result you will get the outputs like,

command - db.result.find({})

output -

    "_id" : "XXX", 

    "value" : 3.0

}

    "_id" : "XXX", 

    "value" : 2.0

}

...

Answer is