使用Spring Data Repository向mongo JSON @Query添加排序

时间:2011-10-13 11:12:27

标签: java spring mongodb spring-data

我想使用mongo JSON queryfind的结果进行排序,并进行了一些阅读和实验,但仍然无法使其工作。我有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 Data中执行此操作。它尝试将它添加到@Query但它没有用,因为我认为Spring只是执行find()

1 个答案:

答案 0 :(得分:5)

您应该只需向查询方法添加Sort参数,从而动态管道将应用于Sort中定义的查询的@Query个实例。

相关问题