How can we implement pagination for the Mongodb collection using mongoTemplate

I am a noob in mongoDb I need to implement Pagination for any specific collection, for example, say

I have a Foo collection and I have a Fucntion that returns all the entries from the Foo collection

public List<Foo> getFoo(){ } 

But I need to retrieve records from Foo, implementing pagination, how can I achieve this using mongoTemplate Spring data mongodb?

+6
source share
2 answers

For general pagination, you can use the .skip() and .limit() in the Query object, which you can pass 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() will show how the results can go, and .skip() will show the returned page size.

Get an instance of MongoOperations from MongoTemplate and use the standard .find() operation .find() .

Skipping and limiting is not the most efficient option, but try to store the last values ​​seen by the natural index, for example, _id , where possible, and use range queries to avoid skipping 1000 results.

  Query query = new Query(); query.addCriteria(Criteria.where("_id").gt(lastSeen)); query.limit(10); 
+11
source

You can provide a pass and limit the query you are using, and this should help pagination. Take a look at the find method in the MongoTemplate class.

Your method should look like this:

 public List<Foo> getFoo(int pageNumber, int pageSize) {...} 
+1
source

Source: https://habr.com/ru/post/974074/


All Articles