title: Calculate average using mapreduce in MongoDb
body: <p>I have a collection of 10 million records which resembles this.</p>
  
  <pre><code>{
      "_id" : ObjectId("596dd10bbd1a6628ace1c14c"),
      "X" : 13212,
      "Z" : 173836,
      "userID" : 9354785
  }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>var mapFunction1 = function() {
  emit(this.userID, this.Z);
  };
  
  var reduceFunction1 = function() {
  return Array.sum(Z);
  };
  
  db.transaction.mapReduce(
  mapfunction1, 
  reduceFunction1,
  {out:"mapreduce"}
  )
  </code></pre>
  
  <p>How do i calculate the average of X?</p>
  
  <p>I tried Array.avg(Z) but it returns the same output as sum(Z).</p>