Spring data mongoRepository Query sort

paul picture paul · May 17, 2013 · Viewed 25.5k times · Source

I was looking to see how I could introduce a sort into a Query annotation in a repository method that I have. I already saw this code in Google and here, but I could not make it works

@Query("find({state:'ACTIVE'}).sort({created:-1}).limit(1)")
    Job findOneActiveOldest();

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

I know that with pagination I can make it, but in some cases I don't need paginate, so I was wondering how to make it with Query annotation.

Any suggestion please?

Answer

Maciej Walkowiak picture Maciej Walkowiak · May 22, 2013

I don't think it is possible to do it with @Query annotation. If you dont need to paginate you can just make your repository method use Sort parameter:

@Query("{ state:'ACTIVE' }")
Job findOneActive(Sort sort);

and use it:

yourRepository.findOneActive(new Sort(Sort.Direction.DESC, "created"))