2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Query with sort() and limit() in Spring Repository interface

I"m new to Spring Data with MongoDB and would like to have an automagically generated query method inside my MongoRepository extension interface which requires filtering, sorting and limiting.

The query looks like this:

// "created" is the field I need to sort against


The repository interface looks like this:

public interface JobRepository extends MongoRepository<Job, String> {

    @Query("{ state: "ACTIVE", userId: ?0 }")

    List<Job> findActiveByUserId(String userId);

    // The next line is the problem, it wont work since

    // it"s not in the format @Query expects


    Job findOneActiveOldest();



I know that one can add a Sort argument to a query method in order to get sorting but the problem is limiting the results to just a single object. Is this possible to do without having to write a custom JobRepositoryImpl?


Example of what I am looking for:

@Query("{ state:"ACTIVE", $orderby: {created:-1}, $limit:1 }")

Job findOneActiveOldest();


@Query("{ state:"ACTIVE" }")

@Sort("{ created:-1 }")


Job findOneActiveOldest();


What's wrong with:

public interface JobRepository extends MongoRepository<Job, String> {

  @Query("{ state : 'ACTIVE' }")

  Page<Job> findOneActiveOldest(Pageable pageable);


and using it:

// Keep that in a constant if it stays the same

PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "created"));

Job job = repository.findOneActiveOldest(request).getContent().get(0);

Answer is