我想find
使用mongo JSON 查询对 a 的结果进行排序,并且做了一些阅读和实验,但我仍然无法让它工作。我有PagingAndSortingRepository并且可以毫无问题地Sort()
在findAll上使用。
存储库类
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'} ] })
而且我知道我可以sort()
在常规的 mongoDb 语法中添加一个,但无法从 Java/Spring Data 中弄清楚如何做到这一点。它尝试将它添加到 @Query 但它不起作用,因为我认为 Spring 只是在执行一个find()
.