这是对旧帖子的答案,但我会提供答案,以防其他人在搜索类似内容时出现。
建立在之前的基础上Fırat KÜÇÜK 的解决方案 https://stackoverflow.com/a/43998962/8031498,将 results.size() 作为 PageImpl 构造函数中“total”字段的值不会使分页按您期望的方式工作。它将总大小设置为页面大小每次,因此,您需要找出查询将返回的实际结果总数:
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;
}
}
运行几乎相同的查询两次似乎效率很低,但是如果您要对结果进行分页,则可分页对象must如果您确实希望其行为像分页一样,请知道结果总数。如果有人可以改进我的方法来获取结果总数,那就太棒了!
Edit:这还将提供计数,并且更简单,因为您不需要包装器对象来保存结果,因此您可以用以下代码块替换整个先前的代码块:
private long getCount(String propertyName, String propertyValue) {
Query countQuery = new Query(Criteria.where(propertyName).is(propertyValue));
return mongoTemplate.count(countQuery, Foo.class);
}