title: MongoDB query to get last record of each id
body: <p>I want to get last record of each <strong>sender.id</strong> based on <strong>createdAt</strong> using mongodb query.</p>
  
  <p>Sample json:</p>
  
  <pre><code>{
      "code" : "34242342",
      "name" : "name1",
      "amount" : 200,
      "sender" : {
          "id" : "fsrfsr3242",
          "name" : "name2",
          "phone" : "12345678",
          "category": "cat1"
      },
      "receiver" : {
          "id" : "42342rewr",
          "name" : "naem3",
          "phone" : "5653679755"
      },
      "message" : "",
      "status" : "done",
      "createdAt" : ISODate("2019-09-27T09:17:32.597Z")
  }
  </code></pre>
  
  <p>Query i tried:</p>
  
  <pre><code>[{
      $match: {
          'sender.category': "cat1"
      }
  }, {
      $group: {
          _id: "$sender.id",
          lastrecord: {
              $last: "$createdAt"
          }
      }
  }]
  </code></pre>
  
  <p>I want to return <strong>entire json</strong> as above with only last record of each sender.id. Above query is only giving me only last date , How do i return entire json using aggregation pipeline?</p>
  
  <p>I am using <strong>groupby</strong> because each sender.id can have multiple records of which i only want to retrieve the last one.</p>