通过 Spring Boot 存储库从 mongoDB 中的集合中获取最大日期

问题描述

我需要从 Spring Boot 存储库的 MongoDB (Compass) 集合中获取最大日期,并且“sendingSystemCode”字段必须等于“999”。

现在我是这样做的:

@Repository
public interface ControlFutureTransactionRepository extends 
MongoRepository<ControlFutureTransactionEntity,Integer>
{
    @Query("{'sendingSystemCode': {$eq: 999}}")
    List<ControlFutureTransactionEntity> getControlFutureTransactionBySendingSystemCode();
}

我通过代码中的一个简单循环获得的最大日期,我希望通过一个查询使代码更快,将最大日期添加到存储库中的方法中。 出于某种原因,这个选项在谷歌中很难找到。

非常感谢!

解决方法

您有两个选择:

选项 1(聚合框架):

db.collection.aggregate([ {$match:{sendingSystemCode:999}},{$group:{_id:"the_max_date",maxDate:{$max:"$createdDate"}}}        ])

选项 2(查找/排序/限制):

db.collection.find({sendingSystemCode:999}).sort({createdDate:-1}).limit(1)