Orkun
Orkun

Reputation: 7228

Spring boot & mongo custom query with order by

I have a custom query in org.springframework.data.mongodb.repository that goes

@Query("{'additionalInfo.suspicious' : true}")
List<Trip> findSuspiciousTripsByFleetId(String fleetId, Pageable pageable);

How could I add a order by (date desc) to this?

Does it magically accept OrderByDateDesc suffix for example?

thanks in advance.

Upvotes: 6

Views: 6256

Answers (1)

pvpkiran
pvpkiran

Reputation: 27018

You can do this by adding a Sort attribute to the method. And pass the sort argument when calling the method.

@Query("{'additionalInfo.suspicious' : true}")
List<Trip> findSuspiciousTripsByFleetId(String fleetId, Sort sort);

And during invocation of this method, do

Sort sort = new Sort(Sort.Direction.DESC, "date")
tripRepository.findSuspiciousTripsByFleetId("fleedtId", sort);  

spring-data will take care of the rest for you.

Upvotes: 9

Related Questions