Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data mongoRepository Query sort

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?

like image 353
paul Avatar asked May 17 '13 11:05

paul


2 Answers

Just use sort parameter of @Query annotation. 1 = ASC, -1 = DESC

    @Query(
        value  = ...,
        sort = "{'details.requestTime': -1}"
    )
like image 191
lukyer Avatar answered Sep 20 '22 05:09

lukyer


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"))
like image 32
Maciej Walkowiak Avatar answered Sep 22 '22 05:09

Maciej Walkowiak