title: sorting a mongodb by week and then suming data and avreging it
body: <p>I am trying to sort a mongodb collection by week and then summing data and averaging it.</p>
  <p>All my documents are identical:</p>
  <pre><code>{
      &quot;flight_date&quot;: {
          &quot;$date&quot;: &quot;2015-01-01T00:00:00.000Z&quot;
      },
      &quot;flight_number&quot;: 20,
      &quot;origin_city&quot;: &quot;San Francisco, CA&quot;,
      &quot;destination_city&quot;: &quot;New York, NY&quot;,
      &quot;delay_in_minutes&quot;: 6,
      &quot;cancelled&quot;: 0
  }
  </code></pre>
  <p>so far my best attempt looks like this</p>
  <pre class="lang-js prettyprint-override"><code>db.flightStats.aggregate([
      {
          $group: { _id: { $week: &quot;$flight_date&quot; } },
          $group: {
              _id: { delay_in_minutes: &quot;$delay_in_minutes&quot; },
              total_delay: { $sum: 1 },
              avgDelay: { $avg: &quot;$delay_in_minutes&quot; }
          }
      },
      { $sort: { avgDelay: -1 } }
  
  ]).pretty()
  </code></pre>