I'm a noob in mongoDb i need to implement Pagination for any specific Collection for instance say
I have a Collection Foo and i have a Fucntion that returns all the records from the Foo collection
public List<Foo> getFoo(){
}
But i need to fetch records from the Foo by implementing pagination how can i achieve this by using mongoTemplate Spring data mongodb?
MongoRepository is an interface provided by Spring Data in the package org. springframework. data. mongodb.
MongoDB and Spring Boot interact using the MongoTemplate class and MongoRepository interface.
For general pagination you can use the .skip()
and .limit()
modifiers on the Query object which you can pass in as arguments to your method:
Query query = new Query();
query.addCriteria(Criteria.where("a").is("b"));
query.skip(10);
query.limit(10);
List<Foo> results = mongoOperation.find(query, Foo);
With .skip()
being how may results to go past and .limit()
being the page size to return.
So derive an instance of MongoOperations from MongoTemplate and use a standard .find()
operation from there.
Skip and limit is not the most performant option though, try to store last seen values on a natural index like _id
where possible and use range queries to avoid "skipping" through 1000's of results.
Query query = new Query();
query.addCriteria(Criteria.where("_id").gt(lastSeen));
query.limit(10);
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