我是使用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)
但这显然不起作用:(
我们正在开发一个从 mongoDB 获取数据的项目。我们创建了存储库类,如下所示
@Repository
public interface CustomerRepository extends MongoRepository<Customer,String>{
List<Customer> customers = findByCustomerId(final String customerId);
}
Run Code Online (Sandbox Code Playgroud)
我们希望添加跳过/偏移和限制参数作为 findByCustomerId 方法的一部分。其中 limit 用于定义返回的记录数,skip/offset 定义我们需要获取记录后的记录数。
请帮助我们如何使用 MongoRepository 以最佳方式实现这一点。