title: MongoDB MapReduce Average Returning Incorrect Result
body: <p>I've got a pretty simpleMap/Reduce function on MongoDB which is meant to be returning the average of a set of data from a collection. It all seems to work okay, except the answers are just wrong, in one case by a factor of 2.</p>
  
  <p>Here are my Map/Reduce functions- I've had to obfuscate where the 'diff' value comes from but from the print statement returned in the log I've verified that its correct:</p>
  
  <pre><code>    var mapFunction = function() {
      if (this.fieldId==1234) {
          print(diff);    
      }
      emit(this.fieldId,diff);
  };
  
  var reduceFunction = function(keyId, viewTime) {
      var count = viewTime.length;
      var total = 0;
      for (idx = 0; idx &lt; viewTime.length; idx++) {
          total+=viewTime[idx];
      }
      if (keyVidId==1234) {
          print('1234: ' + total/count);  
      }
      return total/count;
  };
  </code></pre>
  
  <p>After running this, for the particular record 1234 I get a result which is approximately double what I got before moving from MySQL <em>and</em> also double the result I get from using the Aggregation Framework which I used prior to deciding to do Map/Reduce for scalability etc. Other records are also wrong, but generally not by as much.</p>
  
  <p>Initially the reduceFunction used Array.avg but I converted to a manual average to try and debug.</p>
  
  <p>The data in question is roughly 23,000 documents and each diff tends to be a very large int.</p>
  
  <p>I went through the log trying to find out what went wrong and actually manually averaged the diff values being spat out in the logs using LibreOffice Calc and got the <strong>correct</strong> result, so the error is somewhere in the reduce function implementation.</p>
  
  <p>I noticed in the logs that there are multiple lines where it says "1234: ", as if the reduce function is being called multiple times for a single keyId- I'm not sure quite how this is working underneath but I imagine its splitting the workload into multiple function calls and then combining at the end, which would mean it would have to weight the results to get the correct average...which I imagine is where the problem may lie, but I'm not sure. I was also worried about it being an int32 overflow (because the sum of all the diffs is larger than the max) but it doesn't seem to be the case from tinkering a little in python with the numbers in question.</p>
  
  <p>Hopefully someone can shed some light on what MongoDB is doing in the background and what I'm doing wrong...</p>
  
  <p>Thanks!</p>