title: How can I aggregate documents by time interval in MongoDB?
body: <p>I need to aggregate my collection based on a certain time interval. </p>
  
  <p>As you may think, I don´t need to count e.g. per hour our day.</p>
  
  <p>I need to aggregate based on a 30 minutes interval (or any other). Lets say, the first document was created at 3:45PM. Then there are 5 more documents, created between 3:45PM and 4:15PM.
  So in this time interval, I have 6 documents. So the first document of the MapReduce result is a document with the count of 6.</p>
  
  <p>Let´s say, the next document is created ad 4:35PM and three more at 4:40PM. </p>
  
  <p>So the next document of the MapReduce result is a document with the count of 4.</p>
  
  <p>And so on...</p>
  
  <p>Currently my map function looks like this:</p>
  
  <pre><code>var map = function() {                                    
          var key = {name: this.name, minute: this.timestamp.getMinutes()};
          emit(key, {count: 1})
  };
  </code></pre>
  
  <p>So nothing special. Currently I group by the minute, which is not what I want at the end. Here, instead of minute, I need to be able to check the time-interval described above.</p>
  
  <p>And my reduce function:</p>
  
  <pre><code>var reduce = function(key, values)
  {
     var sum = 0;
     values.forEach(function(value)
     {
         sum += value['count'];
     });
     return {count: sum};
  };
  </code></pre>
  
  <p>The output of this is like that:</p>
  
  <pre><code>{
  0: "{ "_id" : { "name" : "A" , "minute" : 11.0} , "value" : { "count" : 1.0}}",
  1: "{ "_id" : { "name" : "B" , "minute" : 41.0} , "value" : { "count" : 6.0}}",
  2: "{ "_id" : { "name" : "B" , "minute" : 42.0} , "value" : { "count" : 3.0}}",
  3: "{ "_id" : { "name" : "C" , "minute" : 41.0} , "value" : { "count" : 2.0}}",
  4: "{ "_id" : { "name" : "C" , "minute" : 42.0} , "value" : { "count" : 2.0}}",
  5: "{ "_id" : { "name" : "D" , "minute" : 11.0} , "value" : { "count" : 1.0}}",
  6: "{ "_id" : { "name" : "E" , "minute" : 16.0} , "value" : { "count" : 1.0}}"
  }
  </code></pre>
  
  <p>So it counts / aggregates documents per minute, but NOT by my custom time interval.</p>
  
  <p>Any ideas about this?</p>