Jose
Jose

Reputation: 1829

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.

Upvotes: 2

Views: 7004

Answers (3)

KAVIMATHI P R
KAVIMATHI P R

Reputation: 1

Use this code in spring to get the latest updated time from mongodb: (mongoTemplate)

public List getTopPosts() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.DESC, "postUploadedTime"));
        return mongoTemplate.find(query,Post.class);
    }

Upvotes: 0

Numbernick
Numbernick

Reputation: 181

You can use the spring data method syntax like: public User findTopByOrderByUpdateTimeAsc()

A reference can be found here: https://www.baeldung.com/jpa-limit-query-results#1first-ortop

Upvotes: 4

Orest
Orest

Reputation: 6748

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

Upvotes: 4

Related Questions