[英]How can we implement Pagination for Mongodb Collection using mongoTemplate
I'm a noob in mongoDb i need to implement Pagination for any specific Collection for instance say 我是mongoDb中的菜鸟,我需要为任何特定的集合实现Pagination,例如说
I have a Collection Foo and i have a Fucntion that returns all the records from the Foo collection 我有一个Collection Foo,我有一个Fucntion,它返回Foo集合中的所有记录
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? 但我需要通过实现分页从Foo中获取记录如何通过使用mongoTemplate Spring数据mongodb实现这一目标?
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对象上使用
.skip()
和.limit()
修饰符,您可以将这些修饰符作为参数传递给您的方法:
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. 使用
.skip()
结果,并且.limit()
是要返回的页面大小。
So derive an instance of MongoOperations from MongoTemplate and use a standard .find()
operation from there. 因此从MongoTemplate派生一个MongoOperations实例,并从那里使用标准的
.find()
操作。
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. 跳过和限制不是最高性能的选项,尽可能将最后看到的值存储在像
_id
这样的自然索引上,并使用范围查询来避免“跳过”1000的结果。
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.
看一下MongoTemplate类中的方法find 。
Your method should look like this: 您的方法应如下所示:
public List<Foo> getFoo(int pageNumber, int pageSize) {...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.