我想在最近的日期找到用户(假设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}
查询应该返回
{{userId:1, date:20}, {userId:2, date:50}, {userId:3, date:30}}
我正在使用的聚合方法是
db.table1.aggregate({$group:{'_id':'$userId', 'max':{$max:'$date'}}},
{$sort:{'max':1}}).result
答案 0 :(得分:5)
您可以先按日期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);