user2984914
user2984914

Reputation: 83

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

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.

Upvotes: 8

Views: 21779

Answers (2)

MattSenter
MattSenter

Reputation: 3120

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.

Upvotes: 18

Ajay George
Ajay George

Reputation: 11875

$limit is what you need.

Limit - http://docs.mongodb.org/manual/reference/method/cursor.limit/#cursor.limit

mongos> db.test.find()
{ "_id" : 1, "status" : "Failed" }
{ "_id" : 2, "status" : "Pass" }
{ "_id" : 3, "status" : "Failed" }
{ "_id" : 4, "status" : "Pass" }
{ "_id" : 5, "status" : "Failed" }
{ "_id" : 6, "status" : "Pass" }
{ "_id" : 7, "status" : "Failed" }
{ "_id" : 8, "status" : "Pass" }
{ "_id" : 9, "status" : "Failed" }
{ "_id" : 10, "status" : "Pass" }
mongos> db.test.find({status: "Failed"})
{ "_id" : 1, "status" : "Failed" }
{ "_id" : 3, "status" : "Failed" }
{ "_id" : 5, "status" : "Failed" }
{ "_id" : 7, "status" : "Failed" }
{ "_id" : 9, "status" : "Failed" }
mongos> db.test.find({status: "Failed"}).limit(3)
{ "_id" : 1, "status" : "Failed" }
{ "_id" : 3, "status" : "Failed" }
{ "_id" : 5, "status" : "Failed" }

Upvotes: -5

Related Questions