Using this answer I have created a Mongodb query that brings objects paginated and sorted and also adds the total no. of objects. What I can't do now is translate that into java Code
db.messages.aggregate([
    { $match: { _id: {$exists: true} },
    { $sort: { _id: 1 } }, // here you can sort using other field 
    { $group: {
        _id: null,
    messagesCount: { $sum: 1 },
    allMessages: {
      $push: '$$ROOT'
    }
  } }
  { $project: {
    _id: 0,
    messagesCount: 1,
    messagesPage: {
      $slice: ['$allMessages', 0, 30] //pageNo=0, pageSize=30
    }
  } }
])
MatchOperation and SortOperation were pretty straight forward. java Code:
MatchOperation matchOperation = new MatchOperation(Criteria.where("_id").exists(true));
SortOperation sortOperation = new SortOperation(new Sort(Sort.Direction.DESC, "_id"));
//HOW DO I TRANSLATE THESE TWO IN JAVA CODE?
GroupOperation groupOperation = Aggregation.group()....**???**
ProjectionOperation projectOperation = Aggregation.project()...**???**
mongoTemplate.aggregate(
            newAggregation(matchOperation, sortOperation, groupOperation, 
            projectOperation), 
            "messages", 
            MessagesSortedAndPaginated.class);
MessagesSortedAndPaginated class:
public class MessagesSortedAndPaginated {
    private long totalCount;
    private List<Message> messagesPage;
}
Message class:
 @Document(collection = "messages")
 public @Data class Message implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        private String id;
    ...