title: Mongodb - to group documents and get document from each group with max value of a field
body: <p>I have a Mongo collection where the documents are never updated, rather the most current document is read, and a new document is inserted with some fields updated on it. These common documents share an identifier <code>document_identifier</code> that distinguishes them from others.</p>
  
  <p>I want to perform a query that performs the following:
  Get all documents whose <code>customer_id</code> is X, group them by their <code>document_identifier</code>, and from each group take the document with the max <code>updated_at</code> timestamp. It should return the documents in their entirety (all of their properties).</p>
  
  <p>Example data set:</p>
  
  <pre><code>{
      document_identifier: "abc",
      updated_at: 1000,
      customer_id: "123",
      ...  
  },
  
  {
      document_identifier: "def",
      updated_at: 1001,
      customer_id: "123",
      ...
  },
  
  {
      document_identifier: "abc",
      updated_at: 1002,
      customer_id: "123",
      ...
  },
  
  {
      document_identifier: "def",
      updated_at: 10003,
      customer_id: "123",
      ...
  },
  
  {
      document_identifier: "xyz",
      updated_at: 1004,
      customer_id: "999",
      ...
  },
  
  {
      document_identifier: "abc",
      updated_at: 1005,
      customer_id: "123",
      ...
  },
  
  {
      document_identifier: "def",
      updated_at: 1006,
      customer_id: "123",
      ...
  },
  
  </code></pre>
  
  <p>In the above example if I wanted to query on <code>customer_id</code> of "123" the result would be:</p>
  
  <pre><code>{
      document_identifier: "abc",
      updated_at: 1005,
      customer_id: "123",
      ...
  },
  
  {
      document_identifier: "def",
      updated_at: 1006,
      customer_id: "123",
      ...
  },
  </code></pre>
  
  <p>I've been steered towards the Mongo aggregate framework but can't seem to get it.</p>
  
  <p>Any help is greatly appreciated.</p>
  
  <p>EDIT: This is what I have right now and it appears to be working, but I'm not sure that it's the most optimal:</p>
  
  <pre><code>db.my_colleciton.aggregate([
      {
         $match: {customer_id: &lt;value to query on&gt;}
      },
  
      {
          $sort: {updated_at: -1}
      },
  
      {
          $group: {
              _id: "$document_identifier",
              my_doc: {$first: "$$ROOT"}
          }
      },
  
      {
          "$replaceRoot": {newRoot: "$my_doc"}
      }
  ])
  </code></pre>