How can we implement Pagination for Mongodb Collection using mongoTemplate

百般思念 提交于 2019-12-04 05:06:29

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);

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

Your method should look like this:

public List<Foo> getFoo(int pageNumber, int pageSize) {...}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!