开发者

Adding sort to mongo JSON @Query with Spring Data Repository

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() {
        r开发者_运维问答eturn (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().


You should be able to simply add a Sort parameter to the query method and thus dynamically pipe in Sort instances that will be applied to the query defined in @Query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜