我们如何使用mongoTemplate实现Mongodb Collection的分页 [英] How can we implement Pagination for Mongodb Collection using mongoTemplate
问题描述
我是mongoDb的菜鸟,我需要为任何特定的Collection实现分页
I'm a noob in mongoDb i need to implement Pagination for any specific Collection for instance say
我有一个Foo集合,并且我有一个Fucntion可以返回Foo集合中的所有记录
I have a Collection Foo and i have a Fucntion that returns all the records from the Foo collection
public List<Foo> getFoo(){
}
但是我需要通过实现分页从Foo获取记录,如何使用mongoTemplate Spring数据mongodb来实现此目的?
But i need to fetch records from the Foo by implementing pagination how can i achieve this by using mongoTemplate Spring data mongodb?
推荐答案
对于常规分页,可以在Query对象上使用.skip()
和.limit()
修饰符,您可以将它们作为方法的参数传递给该对象:
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);
.skip()
是可能的结果,.limit()
是要返回的页面大小.
With .skip()
being how may results to go past and .limit()
being the page size to return.
因此从MongoTemplate派生MongoOperations的实例,然后从那里使用标准的.find()
操作.
So derive an instance of MongoOperations from MongoTemplate and use a standard .find()
operation from there.
跳过和限制并不是最有效的选择,尝试将最后一次看到的值存储在像_id
这样的自然索引上,并使用范围查询来避免跳过" 1000个结果.
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);
这篇关于我们如何使用mongoTemplate实现Mongodb Collection的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!