通过Spring MongoTemplate进行聚合以获取集合的最大值

pau*_*aul 4 java spring mongodb spring-data spring-mongodb

我想在最近的日期找到用户(假设User对象有一个date字段).数据存储在MongoDB中,并通过Spring访问MongoTemplate.

原始数据示例:

{userId:1, date:10}
{userId:1, date:20}
{userId:2, date:50}
{userId:2, date:10}
{userId:3, date:10}
{userId:3, date:30}
Run Code Online (Sandbox Code Playgroud)

查询应该返回

 {{userId:1, date:20}, {userId:2, date:50}, {userId:3, date:30}}
Run Code Online (Sandbox Code Playgroud)

我正在使用的聚合方法是

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

小智 6

您可以先按日期DESC对其进行排序,然后选择第一个按用户ID分组

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);
Run Code Online (Sandbox Code Playgroud)