title: MongoDB aggregation wtih distinct value in Java?
body: <p>I am trying to get the latest entered document based upon a unique ID. Here is the collection</p>
  <pre><code>{
          &quot;_id&quot; : &quot;535f5d074f075c37fff4cc74&quot;,
          &quot;senderId&quot; : 8989898,
          &quot;receiverId&quot; : 8686868,
          &quot;channelId&quot; : &quot;909090&quot;,
          &quot;createdAt&quot;: 1
  }
  {
          &quot;_id&quot; : &quot;535f5d074f075c37fff4cc74&quot;,
          &quot;senderId&quot; : 8989898,
          &quot;receiverId&quot; : 8686868,
          &quot;channelId&quot; : &quot;909090&quot;
          &quot;createdAt&quot;: 2
  }
  {
          &quot;_id&quot; : &quot;535f5d074f075c37fff4cc74&quot;,
          &quot;senderId&quot; : 8989898,
          &quot;receiverId&quot; : 10101010,
          &quot;channelId&quot; : &quot;919191&quot;
          &quot;createdAt&quot;: 3
  }
  </code></pre>
  <p>The result will be :</p>
  <pre><code>{
          &quot;_id&quot; : &quot;535f5d074f075c37fff4cc74&quot;,
          &quot;senderId&quot; : 8989898,
          &quot;receiverId&quot; : 8686868,
          &quot;channelId&quot; : &quot;909090&quot;
          &quot;createdAt&quot;: 2
  }
  {
          &quot;_id&quot; : &quot;535f5d074f075c37fff4cc74&quot;,
          &quot;senderId&quot; : 8989898,
          &quot;receiverId&quot; : 10101010,
          &quot;channelId&quot; : &quot;919191&quot;
          &quot;createdAt&quot;: 3
  }
  </code></pre>
  <p>Providing the elements with distinct <code>channelId</code> keyword and the latest created with in <code>channelId</code>.</p>
  <p>I tried the following approach:</p>
  <pre><code>Aggregation aggregation = Aggregation.newAggregation(
              Aggregation.sort(Sort.Direction.DESC, Constant.CREATED_AT),
              Aggregation.group(Constant.CHANNEL_ID));
  
  return mongoTemplate.aggregate(aggregation, &quot;tbl_message&quot;, Messages.class)
              .getMappedResults()
              .stream()
              .distinct()
              .collect(Collectors.toList());
  </code></pre>
  <p>The above code is just providing me distinct channelId (s) in the entire collection. How can I correct the above statement as per the requirements?</p>