【问题标题】:Aggregate via Spring MongoTemplate to get max value of a collection通过 Spring MongoTemplate 聚合以获取集合的最大值
【发布时间】:2023-03-20 00:29:01
【问题描述】:

我想按最近的日期查找用户(假设 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

【问题讨论】:

  • 在您的预期结果中,您有两个 userId 3 条目 - 这是故意的吗?此外,您使用的聚合将按日期对结果进行排序,但您的预期结果按 ID 排序 - 您想要哪一个?

标签: java spring mongodb spring-data spring-mongodb


【解决方案1】:

您可以先按日期 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);

【讨论】:

  • newAggregation 是一个静态工厂方法,我们将聚合操作列表传递给它。
猜你喜欢
  • 2020-09-28
  • 1970-01-01
  • 2016-04-08
  • 1970-01-01
  • 2021-08-16
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 2017-12-10
相关资源
最近更新 更多