title: How to handle partial week data grouping in mongodb
body: <p>I have some docs (daily open price for a stock) like the followings:</p>
  
  <pre><code>/* 0 */
  {
      "_id" : ObjectId("54d65597daf0910dfa8169b0"),
      "D" : ISODate("2014-12-29T00:00:00.000Z"),
      "O" : 104.98
  }
  
  /* 1 */
  {
      "_id" : ObjectId("54d65597daf0910dfa8169af"),
      "D" : ISODate("2014-12-30T00:00:00.000Z"),
      "O" : 104.73
  }
  
  /* 2 */
  {
      "_id" : ObjectId("54d65597daf0910dfa8169ae"),
      "D" : ISODate("2014-12-31T00:00:00.000Z"),
      "O" : 104.51
  }
  
  /* 3 */
  {
      "_id" : ObjectId("54d65597daf0910dfa8169ad"),
      "D" : ISODate("2015-01-02T00:00:00.000Z"),
      "O" : 103.75
  }
  
  /* 4 */
  {
      "_id" : ObjectId("54d65597daf0910dfa8169ac"),
      "D" : ISODate("2015-01-05T00:00:00.000Z"),
      "O" : 102.5
  }
  </code></pre>
  
  <p>and I want to aggregate the records by week so I can get the weekly average open price. My first attempt is to use:</p>
  
  <pre><code>db.ohlc.aggregate({
      $match: {
          D: {
              $gte: new ISODate('2014-12-28')
          }
      }
  }, {
      $project: {
          year: {
              $year: '$D'
          },
          week: {
              $week: '$D'
          },
          O: 1
      }
  
  }, {
      $group: {
          _id: {
              year: '$year',
              week: '$week'
          },
          O: {
              $avg: '$O'
          }
      }
  }, {
      $sort: {
          _id: 1
      }
  })
  </code></pre>
  
  <p>Bu I soon realized the result is incorrect as both the last week of 2014 (week number 52) and the first week of 2015 (week number 0) are partial weeks. With this aggregation I would have an average price for 12/29-12/31/2014 and another one for 01/02/2015 (which is the only trading date in the first week of 2015) but in my application I would need to group the data from 12/29/2015 through 01/02/2015. Any advice?</p>