title: MongoDB aggregation by time interval PHP
body: <p>I'm using MongoDB to store server statistics that are captured every 15 seconds (so 4 rows get inserted each minute per server) and am trying to get this data plotted onto a graph for all data between a certain timestamp.</p>
  
  <p>For example, the following query can be used:</p>
  
  <pre><code>$tbl-&gt;find(
    array(
      "timestamp" =&gt; array('$gte' =&gt; '1396310400', '$lte' =&gt; '1396915200'), 
      "service" =&gt; 'a715feac3db42f54edbc50ef6fa057b3'
    ),
    array("timestamp" =&gt; 1, "system" =&gt; 1)
  );
  </code></pre>
  
  <p>Which spits our a bunch of rows that look like this:</p>
  
  <pre><code>Array
  (
      [53933ad8532965621d97dd3b] =&gt; Array
          (
              [_id] =&gt; MongoId Object
                  (
                      [$id] =&gt; 53933ad8532965621d97dd3b
                  )
  
              [system] =&gt; Array
                  (
                      [load] =&gt; 0.55
                      [uptime] =&gt; 1171204.47
                      [processes] =&gt; 222
                  )
  
              [timestamp] =&gt; 1396310403
          )
  
  )
  </code></pre>
  
  <p>This works fine for small data ranges, as I can pass this data directly into Flot or HighCharts and let it prettify the time scales itself. However this doesn't work for large data sets (for example querying over a month).</p>
  
  <p>What I'm trying to do is group the data by hour (or 15 minutes), and return the average values (in this example, its system.load that I'm plotting) for that given time period.</p>
  
  <p>I know that the aggregate function is what I need be using, but despite my best efforts I've been unable to get this working. </p>
  
  <p>Right now I'm letting PHP do all of the work (grouping the results by timestamp and working out the averages) but it's extremely slow and I know MongoDB would handle it better.</p>
  
  <p>Any insight would be greatly appreciated!</p>
  
  <p>Edit:
  I've been trying to follow the answer posted here but am still struggling - <a href="https://stackoverflow.com/questions/14120123/mongodb-aggregation-php-group-by-hours">MongoDB Aggregation PHP, Group by Hours</a></p>