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}")
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.
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"?
Thanks in advance.
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);
Then, to call:
yourRecordRepo.findFailedRecords(new PageRequest(0, 10));
// or using the other method:
yourRecordRepo.findByStatus("Failed", new PageRequest(0, 10));
That will fetch the first page of 10 failed Records.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With