title: How to query the most recent records each having a different unique field in mongodb?
body: <p>I am working on creating a chat that displays an x amount of last messages sent and I am using a mongodb database. I am currently using the aggregate framework for more complex queries and have gotten as far as getting unique entries but they are not the most recently sent entries.</p>
  <p><em>I am attempting to get the most recent message records that matches the senderId with different conversationId's to show the last messaged people.</em></p>
  <p><strong>Schema</strong></p>
  <pre><code>const MessageSchema = new mongoose.Schema({
      conversationId: {
          type:mongoose.Schema.Types.ObjectId,
          ref:&quot;Conversation&quot;
      },
      senderId:{
          type:mongoose.Schema.Types.ObjectId,
          required:true,
          ref:&quot;Users&quot;
      },
      recipientId:{
          type:mongoose.Schema.Types.ObjectId,
          required:true,
          ref:&quot;Users&quot;
      },
      message:{
          type:String
      }
  }, {timestamps:true})
  </code></pre>
  <p><strong>Aggerate query</strong></p>
  <pre><code>    const recentlyMessaged = await MessageModel.aggregate([
          {
              $match:{ senderId:mongoose.Types.ObjectId(currentUserId) }
          },
          {
              $sort: {
                  createdAt: -1
              }
          },
          {
              $group: {_id: &quot;$conversationId&quot;,
              doc: {$first: &quot;$$ROOT&quot;}}
          },
          {
              $limit:3
          },
      ])
  </code></pre>