Search code examples
spring-data-mongodb

Retrieve Max value from a field using Spring Data and MongoDB


I want to obtain the maximum value of the field code within my User entity, using Spring Data and MongoDB.

I have seen similar examples using as below,

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

But have no idea how to integrate it into my own repository using the @Query annotation.

Any alternative solution, than to return the maximum value of said field is also welcome. Thank you.


Solution

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

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

    Additional methods for repository:

    public interface UserRepositoryCustom {
        User maxUser();
    }
    

    And then implementation of it:

    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)
        }
    }