Aggregate via Spring MongoTemplate to get max value of a collection

6.2k views Asked by At

I want to find users by most recent date (Assume the User object has a date field). The data is stored in MongoDB and accessed via a Spring MongoTemplate.

Example of the raw data:

{userId:1, date:10}
{userId:1, date:20}
{userId:2, date:50}
{userId:2, date:10}
{userId:3, date:10}
{userId:3, date:30}

The query should return

 {{userId:1, date:20}, {userId:2, date:50}, {userId:3, date:30}}

The aggregation method Ï am using is

db.table1.aggregate({$group:{'_id':'$userId', 'max':{$max:'$date'}}}, 
{$sort:{'max':1}}).result
1

There are 1 answers

1
Lealem Admassu On BEST ANSWER

You could Sort it first by date DESC and select the first while grouping by userID

final Aggregation aggregation = newAggregation(
    Aggregation.sort(Sort.Direction.DESC, "date"),
    Aggregation.group("userId").first("date").as("Date")
);

final AggregationResults<User> results = mongoTemplate.aggregate(aggregation, "user", User.class);