使用Spring数据存储库为mongo JSON @Query添加排序



我想使用mongo JSON查询对find的结果进行排序,并做了一些阅读和实验,我仍然无法让它工作。我已经得到了PagingAndSortingRepository,可以在findAll上使用Sort(),没有问题。

库类
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
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
    }
}

查询直接转换为mongoDb调用,这工作得很好

db.things.find({ name:'xxx', $or : [ { state:'new' }, {state:'updated'} ] })

,我知道我可以在常规mongoDb语法中添加sort(),但无法从Java/Spring数据中找出如何做到这一点。它试图将其添加到@查询,但它不起作用,因为我认为Spring只是执行find()

您应该能够简单地将Sort参数添加到查询方法中,从而动态地将Sort实例应用于@Query中定义的查询。

最新更新