Spring存储库中的MongoDB查询:过滤后的记录数限制 [英] MongoDB query in Spring repository: limit number of records after filter
问题描述
我有以下查询(为简单起见,使用了硬编码的参数),使用Spring存储库中的"@Query"注释:
I have the following query (with hard-coded parameters for simplicity) , using the "@Query" annotation within a Spring repository:
@Query("{$ query:{status:'Failed'},$ maxScan:10}")
@Query("{$query : {status:'Failed'}, $maxScan: 10}")
此查询的目的是从数据库中读取状态为失败"的前10条记录(这些记录是系统作业).但是,查询将首先读取10条记录,然后从那10条记录中读取状态为失败"的记录.
The intent of this query is to read the first 10 records from the database that have a status of "Failed" (the records are system jobs). However, the query will first read 10 records, then read records with a status of "Failed" from those 10 records.
我需要在应用过滤器之后而不是之前将限制应用于结果集.如何修改上述查询,以返回应用过滤器逻辑后读取的结果集的前10条记录,即状态为失败"的前10条记录?
I need to apply the limit to a resultset after the filter is applied, not before. How can I modify the above query to return the first 10 records of the resultset that is read after the filter logic is applied, i.e. the first 10 records with a status of "Failed"?
谢谢.
推荐答案
在使用Spring Data MongoDB时,我认为通常您会希望使用Pageable
接口进行这些查询.示例:
When using Spring Data MongoDB, I think generally you'll want to use the Pageable
interface for these queries. Example:
@Query("{status: 'Failed'}")
List<Record> findFailedRecords(Pageable pageable);
// or even better without the @Query annotation just:
List<Record> findByStatus(String status, Pageable pageable);
然后致电:
yourRecordRepo.findFailedRecords(new PageRequest(0, 10));
// or using the other method:
yourRecordRepo.findByStatus("Failed", new PageRequest(0, 10));
这将获取10条失败记录的首页.
That will fetch the first page of 10 failed Records.
这篇关于Spring存储库中的MongoDB查询:过滤后的记录数限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!