title: MongoDb, query the last, and group by
body: <p>I m actually having trouble when dealing with MongoDb.</p>
  
  <p>I need to :</p>
  
  <ul>
  <li>get all of the last entries</li>
  <li>concerning a field</li>
  <li>like : SELECT MAX(id), foreignKey FROM t_table GROUP BY foreignKey</li>
  </ul>
  
  <p>I know that we can use $last with mongodb, but I dont know at all how to proceed.</p>
  
  <p>I tried :</p>
  
  <pre><code>db.collection.aggregate(
     [
       {
         $group:
           {
             _id: "$zone._id",
             lastRegistered: { $last: "$_id" }
           }
       }
     ]
  )
  </code></pre>
  
  <p>But it does'nt seems to give me what I need</p>
  
  <p><strong>EDIT WITH EXAMPLE</strong></p>
  
  <p>According to this three:</p>
  
  <pre><code>  { _id: 55d5a01f9f58d2cc0eb79f5d,
      controlDate: Thu Aug 20 2015 11:38:40 GMT+0200 (Paris, Madrid (heure d’été)),
      zone:
       { _id: 55cb5bb42d191d2022c5c266,
         zoneName: 'Syphon 1',
       },
      actif: true 
      },
  
  
  
    { _id: 55d59f129f58d2cc0eb79f5c,
      controlDate: Fri Aug 21 2015 07:34:12 GMT+0200 (Paris, Madrid (heure d’été)),
      zone:
       { _id: 55cb5bb42d191d2022c5c266,
         zoneName: 'Syphon 1',
       },
      actif: true 
      }
  
  
  
    { _id: 55d5a01f9f58d2cc0eb79f5e,
          controlDate: Fri Aug 20 2015 08:38:40 GMT+0200 (Paris, Madrid (heure d’été)),
          zone:
           { _id: 55cb5bb42d191d2022c5c278,
             zoneName: 'Other zone',
           },
          actif: true 
          },
  </code></pre>
  
  <p>I need to get :</p>
  
  <pre><code>  { _id: 55d59f129f58d2cc0eb79f5c,
      controlDate: Fri Aug 21 2015 07:34:12 GMT+0200 (Paris, Madrid (heure d’été)),
      zone:
       { _id: 55cb5bb42d191d2022c5c266,
         zoneName: 'Syphon 1',
       },
      actif: true 
      }
  
  
  
    { _id: 55d5a01f9f58d2cc0eb79f5e,
          controlDate: Fri Aug 20 2015 08:38:40 GMT+0200 (Paris, Madrid (heure d’été)),
          zone:
           { _id: 55cb5bb42d191d2022c5c278,
             zoneName: 'Other zone',
           },
          actif: true 
          },
  </code></pre>
  
  <p>Which means : I need to get the last (by id or date, never mind) of this collection grouped by the Zone _id. (2 lines, because I have 2 dataset for ONE zone (I need only the last) and I need the last of the other zone (only 1 line so..))</p>
  
  <p>Do you know what I mean ?</p>