我是使用MongoDB的Spring Data的新手,我希望在MongoRepository扩展接口中有一个自动生成的查询方法,需要过滤,排序和限制.
查询如下所示:
// 'created' is the field I need to sort against
find({state:'ACTIVE'}).sort({created:-1}).limit(1)
Run Code Online (Sandbox Code Playgroud)
存储库界面如下所示:
public interface JobRepository extends MongoRepository<Job, String> {
@Query("{ state: 'ACTIVE', userId: ?0 }")
List<Job> findActiveByUserId(String userId);
// The next line is the problem, it wont work since
// it's not in the format @Query expects
@Query("find({state:'ACTIVE'}).sort({created:-1}).limit(1)")
Job findOneActiveOldest();
...
}
Run Code Online (Sandbox Code Playgroud)
我知道可以将一个Sort参数添加到查询方法中以便进行排序,但问题是将结果限制为仅一个对象.这可以在不必编写自定义JobRepositoryImpl的情况下完成吗?
谢谢
编辑:
我正在寻找的例子:
@Query("{ state:'ACTIVE', $orderby: {created:-1}, $limit:1 }")
Job findOneActiveOldest();
Run Code Online (Sandbox Code Playgroud)
要么
@Query("{ state:'ACTIVE' }")
@Sort("{ created:-1 }")
@Limit(1)
Job findOneActiveOldest();
Run Code Online (Sandbox Code Playgroud)
但这显然不起作用:(
使用最新的 Spring Data Mongo(撰写本文时为 2.1.1),如何指定获取“自定义”查询方法的第一条记录?下面是一个例子:
@Query(value="{name: ?0, approval: {'$ne': null}}",
sort="{'approval.approvedDate': -1}",
fields = "{ _id: 1 }")
List<Item> getLatestApprovedIdByName(String name, Pageable pageable);
/**
* Finds the id of the most recently approved document with the given name.
*/
default Item getLatestApprovedIdByName(String name) {
return getLatestApprovedIdByName(name, PageRequest.of(0, 1)).stream().findFirst().orElse(null);
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我可以只使用 String 参数来注释 getLatestApprvedIdByName。org.springframework.data.mongodb.repository.Query注释上似乎没有限制字段。这看起来很奇怪,因为我可以模拟命名方法所做的一切,除了“findFirst”。如果没有 Pageable,我得到IncorrectResultSizeDataAccessException,并且返回 aList是不可接受的,因为我不想浪费时间返回任意大的结果,加上需要处理 0 或 1 个项目的可能性的复杂代码。
我想使用 Spring Data MongoDB 查询 mongo 集合中的子列表。我的代码就像
public interface SomeRepo extends MongoRepository<SomeDoc, String> {
@Query("{'field0': ?0, 'field1': ?1}, {'limit':?2, 'skip':?3}")
List<SomeDoc> findAllByField0AndFiled1(
Long field0,
Long field1,
Long limit,
Long skip
);
}
Run Code Online (Sandbox Code Playgroud)
但limit&skip不在查询对象中
日志是
Created query Document{{field0=123, field1=456}} for Document{{}} fields.
如何将它们传递到查询对象中?