title: mongodb aggregation - group with last on date
body: <p>My mongodb collection include 3 fields: number, date, type.
  What I want to know is how much documents includes the most recent date for their number and has type=3. In pasudo code what I am trying to find will look like this:</p>
  
  <pre><code>Set&lt;String&gt; numbers; //set includes the numbers in the documents
  int result = 0;
  for each (String thisNumber: numbers)
  {
      //find all the documents with this number
      List&lt;Document&gt; documentsWithThisNumber = collection.find({number: "$thisNumber"});
      //find the one with the most recent date with this number
      documentsWithThisNumber = documentsWithThisNumber.sort();
      Document recentDate = documentsWithThisNumber.get(documentsWithThisNumber.size()-1);
      //if this recent document has type 3 we want to count it
      if (recentDate.getType()==3)
          result++;
  }
  </code></pre>
  
  <p>I tried to build a query that will group by the number, and take the last/max date on each number and match the ones their type equal to 3. Since the group can contain only accumulators, and I needed to save the "type" field also for the match, I used the "first" accumulator for the "type" field. I assumed that after it will pick up the document with recent event for each number, this accumulator will just bring me the type of this document.
  My query was:</p>
  
  <pre><code>db.collection.aggregate([
  {$group: {_id: {"number" : "$number"}, "recentDate" : {$max : "$date"}, 
  "recentType" : {$first : "$type"}}},
  {$match: {"recentType" : 3}},
  {$count: "Qty"}
  ],{allowDiskUse: true});
  </code></pre>
  
  <p>The result of this query is wrong, and in addition I discovered that if I switch the $max to $min/$first/$last or if I move it after the "recentType"- I still get the same wrong result, what cause me to think that the "recentDate" doesn't effects the query at all. </p>
  
  <p>Maybe someone has an idea how to build such a query?</p>