title: MongoDB aggregation for distinct values
body: <p>I have 2 collections:</p>
  
  <p><strong>user</strong></p>
  
  <pre><code>{
  _id: 'user_id1',
  username: 'user1',
  }
  
  {
  _id: 'user_id2',
  username: 'user2',
  }
  
  {
  _id: 'user_id3',
  username: 'user3',
  }
  </code></pre>
  
  <p><strong><em>inbox</em></strong>   </p>
  
  <pre><code>{
  _id: 'inbox_id1',
  from: {_id: 'user_id1', username: 'user1'},
  to: {_id: 'user_id2', username: 'user2'},
  text: 'Hello there',
  timestamp: new Date(),
  }
  
  {
  _id: 'inbox_id2',
  from: {_id: 'user_id1', username: 'user1'},
  to: {_id: 'user_id2', username: 'user2'},
  text: 'Trying again...',
  timestamp: new Date(),
  }
  
  {
  _id: 'inbox_id3',
  from: {_id: 'user_id3', username: 'user3'},
  to: {_id: 'user_id2', username: 'user2'},
  text: 'You there?',
  timestamp: new Date(),
  }
  </code></pre>
  
  <p>Whenever a user goes into his inbox, I would like to show him the thread list, which should include a list of latest messages from each user. So basically I would like to get distinct documents (based on the <code>from._id</code> field), and only the latest document (based on <code>timestamp</code> field).</p>
  
  <p>So my results for <code>user2</code> should include only 2 documents (<code>inbox_id2</code> and <code>inbox_id3</code>).</p>
  
  <p>I know I need to use aggregation for it, but not sure how exactly.</p>