简体   繁体   English

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

[英]Get max date from collection in mongoDB by Spring Boot repository

I need to get the max date and the field "sendingSystemCode" need to be equal to '999' from collection in MongoDB (Compass) by Spring Boot repository.我需要从 Spring 引导存储库收集的 MongoDB(指南针)中获取最大日期,并且字段“sendingSystemCode”需要等于“999”。

For now I did it like that:现在我这样做了:

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

And the max date I get by a simple loop in the code, and I want to make the code faster by one query, to add the max date to the method in the repository.以及我通过代码中的一个简单循环获得的最大日期,并且我想通过一个查询使代码更快,以将最大日期添加到存储库中的方法中。 for some reason this option is hard to find in google.由于某种原因,这个选项很难在谷歌中找到。

Thanks a lot !非常感谢 !

You have two options:你有两个选择:

Option 1 (aggregation framework):选项 1(聚合框架):

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

Option 2 ( find/sort/limit):选项 2(查找/排序/限制):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM