title: Group by field(s) and aggregate on max date
body: <p>I have <code>mongo</code> documents of type-</p>
  
  <pre><code>{
      "_id" : ObjectId("77f02ee61df85c423b6a4e79"),
      "client" : "1"
      "type" : "type1",
      "hierarchy" : "hier1",
      "creationDate" : ISODate("2015-09-09T13:06:44Z"),
      "model" : "m1"
  },
  {
      "_id" : ObjectId("77f02ee61df85c423b6a4e80"),
      "client" : "1"
      "type" : "type1",
      "hierarchy" : "hier1",
      "creationDate" : ISODate("2015-09-10T14:06:44Z"),
      "model" : "m2"
  },
  {
      "_id" : ObjectId("77f02ee61df85c423b6a4e81"),
      "client" : "1"
      "type" : "type1",
      "hierarchy" : "hier2",
      "creationDate" : ISODate("2015-09-10T13:06:44Z"),
      "model" : "m3"
  },
  {
      "_id" : ObjectId("77f02ee61df85c423b6a4e82"),
      "client" : "2"
      "type" : "type2",
      "hierarchy" : "hier2",
      "creationDate" : ISODate("2015-09-10T14:06:44Z"),
      "model" : "m4"
  }
  </code></pre>
  
  <p>I want to answer the query - For a given <code>client</code>, fetch all the latest(by <code>creationDate</code>) documents for each <code>type</code> and <code>hierarchy</code> combination (type+hierarchy).</p>
  
  <p>For eg. Output for above data set for <code>client = 1</code> will look like</p>
  
  <pre><code> {
      "_id" : ObjectId("77f02ee61df85c423b6a4e80"),
      "client" : "1"
      "type" : "type1",
      "hierarchy" : "hier1",
      "creationDate" : ISODate("2015-09-10T14:06:44Z"),
      "model" : "m2"
  },
  {
      "_id" : ObjectId("77f02ee61df85c423b6a4e81"),
      "client" : "1"
      "type" : "type1",
      "hierarchy" : "hier2",
      "creationDate" : ISODate("2015-09-10T13:06:44Z"),
      "model" : "m3"
  }
  </code></pre>
  
  <p>I tried to create the query using given flow/pipeline-</p>
  
  <ol>
  <li><code>Match</code> the documents where <code>client = 1</code>   (<code>$match</code> inside aggregate).</li>
  <li><code>group</code> by "list" and "hierarchy"          (<code>$group</code> inside aggregate).   </li>
  <li>I want to aggregate the group of documents in previous step by latest <code>creationDate</code> field. Instead of applying an aggregate function <code>($sum, $avg etc)</code>, I actually want the document with latest <code>creationDate</code> field in each group</li>
  </ol>
  
  <p>But I am stuck at point 3 in the flow. I don't know how to aggregate the documents with same <code>type</code> and <code>hierarchy</code> and select the one with latest date (<code>creationDate</code>) for each type and hierarchy in a single <code>mongo</code> query.</p>