title: Return last document per unique subfield with subfields
body: <p>I'm trying to get the last documents per user in my collection, but I'm not able to retrieve that successfully. I already looked in other posts, but couldn't find (<a href="https://stackoverflow.com/questions/16662405/mongo-group-query-how-to-keep-fields">mongo group query how to keep fields</a> and <a href="https://stackoverflow.com/questions/23360551/mongodb-aggregation-framework-get-last-dated-document-per-grouping-id">MongoDB : Aggregation framework : Get last dated document per grouping ID</a> , for example)</p>
  
  <p><strong>My problem is that I'm not able to return fields as objects apparently</strong> (I'm new to mongo so I hope there is a way).</p>
  
  <p>All I can return are fields like {title, body, username, avatar} and not {title, body, user { username, avatar } }</p>
  
  <p>My collection:</p>
  
  <pre><code>[{
      title: 'title 1',
      body: 'body 2',
      user: {
          username: 'a',
          avatar: 'avatar 1' 
      }
   },
   {
      title: 'title 2',
      body: 'body 2',
      user: {
          username: 'b',
          avatar: 'avatar 2' 
      }
   },
   {
      title: 'title 3',
      body: 'body 3',
      user: {
          username: 'b',
          avatar: 'avatar 2' 
      }
   }]
  </code></pre>
  
  <p>I want to return after group by:</p>
  
  <pre><code>[{
      title: 'title 1',
      body: 'body 2',
      user: {
          username: 'a',
          avatar: 'avatar 1' 
      }
   },
   {
      title: 'title 3',
      body: 'body 3',
      user: {
          username: 'b',
          avatar: 'avatar 2' 
      }
   }]
  </code></pre>
  
  <p>Example of one of the queries I tried:</p>
  
  <pre><code>// this only returns the avatar and not the username...
  db.collection.aggregate([
  { '$sort': { title: 1 } },
  { '$group': { 
      _id: '$user.username',
      body: { $last: '$body' },
      title: { $last: '$title' },
      user: { $last: '$user.username', $last: '$user.avatar' } 
  }}])
  // this throws an error saying the field 'user ' must be an accumulator object
  db.collection.aggregate([
      { '$sort': { title: 1 } },
      { '$group': {
           _id: '$user.username',
           body: { $last: '$body' },
           user: [ { $last: '$user.username', $last: '$user.avatar' } ] 
      }}
   ])
  </code></pre>
  
  <p>With that said, I also want to point out that maybe group is not the way to go. Maybe mongo has a <code>distinct</code> function that I could use?</p>