title: How to generate cumulative results in MongoDB MapReduce
body: <p>I'm just getting started with MapReduce in mongo and have a query with a composite key (date, candidate) that returns a value associated with that key (total number of votes for that candidate on that day).  What I'd actually like is for the number of votes to be cumulative on each date.  That is, for each date/candidate key, the value is a sum of all votes cast for that candidate on and before that date.</p>
  
  <p>Here is my current code:</p>
  
  <p><strong>Example Input:</strong></p>
  
  <pre><code>{
      "interaction" : {
          "type" : "draft",
          "parameters" : {
              "value" : [
                  {
                      "candidate" : 453510,
                      "votes" : 2
                  },
                  {
                      "candidate" : 325786,
                      "votes" : 2
                  }
              ]
          }
      },
      "created_at" : 1360796255
  }
  </code></pre>
  
  <p><strong>Map:</strong></p>
  
  <pre><code>var mapFn = function() {
    var right = function(str, n) {
      return str.substring(str.length, str.length - n);
    }
    var toDate = function(epochTimeSec) {
      var d = new Date(1000 * epochTimeSec);
      var yr = d.getYear() + 1900;
      var mn = d.getMonth() + 1;
      var dt = d.getDate();
      return '' + right('0000' + yr, 4) + '-' + right('00' + mn, 2) + '-' + right('00' + dt, 2);
    }
  
    for(var i=0; i&lt;this.interaction.parameters.value.length; i++)
    {
      vote = this.interaction.parameters.value[i];
      var creationDate = toDate(this.created_at);
      var votedCandidate = vote.candidate;
      emit( {date: creationDate, candidate: votedCandidate}, { quantity: candidate.quantity } );
    }
  }
  </code></pre>
  
  <p><strong>Reduce:</strong></p>
  
  <pre><code>var reduceFn = function(key, values) {
    var sum = 0;
    values.forEach(function(doc) {
      sum += doc.quantity;
    });
    return { quantity: sum };
  }
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>db.collection_mr.drop();
  db.collection.mapReduce(mapFn, reduceFn, { out: 'collection_mr' } );
  
  function printData(r) {
    print(r._id.date + ", " + r._id.candidate + ", " + r.value.quantity);
  }
  
  db.collection_mr.find().forEach(printData);
  </code></pre>
  
  <p>Thank you for any help!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>In response to comments, I've included an example input.  To clarify - the code above correctly returns a sum of all votes cast on each date.  I would like to adapt it, however, to return for each date a total of all votes cast on or before that date.</p>
  
  <p>To answer Asya Kamsky, this is to be run manually on an ad hoc basis, and so needs to output all data before the input date (which may not be the current date).</p>