Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 974
Orkun Ozen Avatar asked Jan 29 '23 09:01

Orkun Ozen


1 Answers

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.

like image 98
pvpkiran Avatar answered Feb 12 '23 08:02

pvpkiran