Calculate average using mapreduce in MongoDb

Viewed 3348

I have a collection of 10 million records which resembles this.

{
    "_id" : ObjectId("596dd10bbd1a6628ace1c14c"),
    "X" : 13212,
    "Z" : 173836,
    "userID" : 9354785
}

User ID is unique. I have to calculate the average of X and sum of Z. I can calculate the sum of Z using the following mapReduce function

var mapFunction1 = function() {
emit(this.userID, this.Z);
};

var reduceFunction1 = function() {
return Array.sum(Z);
};

db.transaction.mapReduce(
mapfunction1, 
reduceFunction1,
{out:"mapreduce"}
)

How do i calculate the average of X?

I tried Array.avg(Z) but it returns the same output as sum(Z).

2 Answers

You are not passing (key,value) pair parameter to reduceFunction1. Try this:

var mapFunction1 = function() {
emit(this.userID, this.Z);
};

var reduceFunction1 = function(varKey,varZ) {
return Array.avg(varZ);
};

db.transaction.mapReduce(
mapfunction1, 
reduceFunction1,
{out:"mapreduce"}
)
Related