mongodbmapreduce

Sum columns mongodb


I have this collection

{a:0,b:1,c:1,d:1}
{a:1,b:1,c:0,d:1}
{a:1,b:1,c:0,d:1}

and I want this result with mapReduce

{id: any, A:2,B:3,C:1,D:3}

but I don't know how do it, I only can sum onde column

how i do this?


Solution

  • You could emit a common key for all the records, in the map function:

    var map = function(){emit(1,this);}
    

    The reduce function would calculate the sum and return the values.

    var reduce = function(key,values){
    var result = {};
    values.forEach(function(i){
     Object.keys(i).forEach(function(key){
     if(result.hasOwnProperty(key)){
        result[key] = i[key]+result[key];
     }
     else{
        result[key] = i[key];
     }
    })
    })
    return result;
    }
    

    Execute the map reduce:

    db.collection.mapReduce(map,reduce,{ out: "out"})
    

    If you knew the keys before hand, then you could easily aggregate the results, using just the $group stage in the pipeline.

    db.collection.aggregate([
    {$group:{"_id":null,
             "a":{$sum:"$a"},
             "b":{$sum:"$b"},
             "c":{$sum:"$c"},
             "d":{$sum:"$d"}}}
    ])