来自字段 Spring Data 和 Mongodb 的最大值 [英] Max value from field Spring Data and Mongodb

查看:35
本文介绍了来自字段 Spring Data 和 Mongodb 的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想计算实体User"中字段代码的最大值,使用Spring Data,我看到代码如下:

I want to calculate the maximum value of the field code within my entity "User", use Spring Data, I have seen that the code is as:

".find({}).sort({"updateTime" : -1}).limit(1)"

但我不知道如何使用@Query 将其集成到我的存储库"中

But I do not know how to integrate it into my "repository" with @Query

或者其他等效的解决方案,而不是返回所述字段的最大值.有人可以帮助我吗?谢谢.

Or another equivalent solution, than to return the maximum value of said field. Can somebody help me? Thank you.

推荐答案

您可以为您的存储库编写自定义方法.例如你有:

You can write a custom method for your repository. For example you have:

public interface UserRepository extends MongoRepository<User, String>, UserRepositoryCustom {
...
}

存储库的其他方法:

public interface UserRepositoryCustom {
    User maxUser();
}

然后实现它:

public class UserRepositoryImpl implements UserRepositoryCustom { 
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public User maxUser() {
        final Query query = new Query()
                .limit(1)
                .with(new Sort(Sort.Direction.DESC, "updateTime"));

        return mongoTemplate.findOne(query, User.class)
    }
}

这篇关于来自字段 Spring Data 和 Mongodb 的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆