在春季数据mongodb中,如何使用mongotemplate或mongo资源库实现聚合的分页。
发布于 2017-05-19 10:40:12
这是对一个旧帖子的回答,但我会给出一个答案,以防其他人在搜索类似的东西时出现。
在前面的solution by Fırat KÜÇÜK的基础上,将results.size()作为PageImpl构造函数中“总计”字段的值,将不会使分页工作像以前那样,那么,您就会期望分页工作正常。它每次将页面大小设置为,因此需要找出查询返回的实际结果总数:
public Page<UserListItemView> list(final Pageable pageable) {
long total = getCount(<your property name>, <your property value>);
final Aggregation agg = newAggregation(
skip(pageable.getPageNumber() * pageable.getPageSize()),
limit(pageable.getPageSize())
);
final List<UserListItemView> results = mongoTemplate
.aggregate(agg, User.class, UserListItemView.class)
.getMappedResults();
return new PageImpl<>(results, pageable, total);
}
现在,获得结果总数的最佳方法是另一个问题,这是我目前正在努力解决的一个问题。我尝试过的方法(它成功了)几乎是运行了两次相同的聚合,一次是为了获得总计数,另一次是为了获得分页的实际结果),但是只使用MatchOperation,然后使用一个GroupOperation来获得计数:
private long getCount(String propertyName, String propertyValue) {
MatchOperation matchOperation = match(Criteria.where(propertyName).is(propertyValue));
GroupOperation groupOperation = group(propertyName).count().as("count");
Aggregation aggregation = newAggregation(matchOperation, groupOperation);
return mongoTemplate.aggregate(aggregation, Foo.class, NumberOfResults.class).getMappedResults().get(0).getCount();
}
private class NumberOfResults {
private int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
两次运行几乎相同的查询似乎有些效率低下,但如果要对结果进行分页,那么可分页对象必须知道结果的总数,如果您真的希望它像分页一样运行。如果有人能改进我的方法来获得结果的总数,那就太棒了!
编辑:这也将提供计数,而且更简单,因为不需要包装器对象来保存结果,因此可以用这个代码块替换整个先前的代码块:
private long getCount(String propertyName, String propertyValue) {
Query countQuery = new Query(Criteria.where(propertyName).is(propertyValue));
return mongoTemplate.count(countQuery, Foo.class);
}
发布于 2017-05-16 10:29:44
除了ssouris solution之外,您还可以使用可访问的类来获取结果。
public Page<UserListItemView> list(final Pageable pageable) {
final Aggregation agg = newAggregation(
skip(pageable.getPageNumber() * pageable.getPageSize()),
limit(pageable.getPageSize())
);
final List<UserListItemView> results = mongoTemplate
.aggregate(agg, User.class, UserListItemView.class)
.getMappedResults();
return new PageImpl<>(results, pageable, results.size())
}
发布于 2015-12-23 14:53:43
您可以使用MongoTemplate
org.spring.framework.data.mongodb.core.aggregation.Aggregation#skip
and
org.springframework.data.mongodb.core.aggregation.Aggregation#limit
Aggregation agg = newAggregation(
project("tags"),
skip(10),
limit(10)
);
AggregationResults<TagCount> results = mongoTemplate.aggregate(agg, "tags", TagCount.class);
List<TagCount> tagCount = results.getMappedResults();
https://stackoverflow.com/questions/34427241
复制相似问题