Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate via Spring MongoTemplate to get max value of a collection

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
like image 610
paul Avatar asked Aug 26 '13 10:08

paul


1 Answers

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);
like image 53
Lealem Admassu Avatar answered Nov 19 '22 19:11

Lealem Admassu