Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB query in Spring repository: limit number of records after filter

Tags:

spring

mongodb

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.

like image 284
user2984914 Avatar asked Nov 12 '13 20:11

user2984914


1 Answers

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.

like image 57
MattSenter Avatar answered Oct 21 '22 04:10

MattSenter