title: Count Distinct Within Date Range
body: <p>I have a MongoDB database with a collection of site-events. The documents look like:</p>
  
  <pre><code>{ 
      "_id" : ObjectId("5785bb02eac0636f1dc07023"), 
      "referrer" : "https://example.com",
      "_t" : ISODate("2016-07-12T18:10:17Z"),
      "_p" : "ucd7+hvjpacuhtgbq1caps4rqepvwzuoxm=", 
      "_n" : "visited site", 
      "km screen resolution" : "1680x1050" 
  },
  
  { 
      "_id" : ObjectId("5785bb02eac0636f1dc07047"), 
      "url" : "https://www.example.com/", 
      "referrer" : "Direct", 
      "_t" : ISODate("2016-07-12T18:10:49Z"), 
      "_p" : "txt6t1siuingcgo483aabmses2et5uqk0=", 
      "_n" : "visited site", 
      "km screen resolution" : "1366x768" 
  },
  
  { 
      "_id" : ObjectId("5785bb02eac0636f1dc07053"), 
      "url" : "https://www.example.com/", 
      "referrer" : "Direct", 
      "_t" : ISODate("2016-07-12T18:10:56Z"), 
      "_p" : "gcama1az5jxa74wa6o9r4v/3k+zulciqiu=", 
      "_n" : "visited site", 
      "km screen resolution" : "1366x768" 
  }
  </code></pre>
  
  <p>I want to get a count of the unique persons within a date range. In SQL it would be </p>
  
  <pre><code>SELECT COUNT(DISTINCT(`_p`)) FROM collection WHERE `_t` &gt; '&lt;SOME DATE&gt;' AND `_t` &lt;= '&lt;SOME OTHER DATE&gt;'
  </code></pre>
  
  <p>So far, I've grouped the dates along using the aggregation pipeline: </p>
  
  <pre><code>db.siteEvents.aggregate(
  
  [
      { 
          $match : {"_n": "visited site"}
      },
  
      {   
          $group : {
  
              _id: {
              year : { $year : "$_t" },        
              month : { $month : "$_t" },        
              day : { $dayOfMonth : "$_t" },
              _p : "$_p"
          },
  
          count: { $sum: 1 }
  
          }
      }, 
  
      {
          $group : {
  
              _id : {
              year : { $year : "$_id.year" },        
              month : { $month : "$_id.month" },        
              day : { $dayOfMonth : "$_id.day" }
              },
  
              count: { $sum: 1 }
          }
      }
  ]
  
  );
  </code></pre>
  
  <p>But this gives errors - I believe because of the second grouping _id trying to grab an intermediate field. I'm currently just using the Mongo shell, but if I had to choose an alternative driver it would be PyMongo. I'd like to get this to work in the shell (so I can understand the process). </p>