I want to sort the results of a find using the mongo JSON query and having done some reading and experimenting, I still can't get it to work. I have got the PagingAndSortingRepository and can use Sort() on findAll with no problems.
Repository class
public interface ThingRepository extends PagingAndSortingRepository<Thing, ObjectId> {
@org.springframework.data.mongodb.repository.Query("{ name:?0, $or : [ { state:'new' } , {state:'updated'} ] }")
List<Device> findThingsInNewOrUpdatedState(String name);
}
Service layer
@Service
public class ThingService() {
@Autowired private ThingRepository thingRepository;
public List<Thing> getSortedThings() {
return (List<Thing>)thingRepository.findAll(new Sort(Sort.Direction.DESC, Arrays.asList("dateModified")));
}
public List<Thing> getNewOrUpdatedThingsSorted() {
return thingRepository.findThingsInNewOrUpdatedState(); // <-- this needs to be sorted
}
}
The query is translated directly into the mongoDb call, which works fine
db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })
and I know I can add a sort() in regular mongoDb syntax but cannot work out how to do this from within Java/Spring Data. It tried adding it to the @Query but it was not working, since I think Spring is just executing a find().