项目场景:
项目场景:最近项目上因为数据量上亿的问题,上了mongodb,主要是用于日志的存储,并设定了过期时间。mongodb分页排序的坑。。。
问题描述
但是mongodb自带的分页效果使用不理想,如果是结合排序,只能在当前页面排序,而不是排序后分页,最后发现,是排序与分页的先后问题导致的。
@Override
public void run() {
List<AggregationOperation> operations = new ArrayList<>();
operations.add(MongoUtils.match("deleted", false));
operations.add(MongoUtils.match("memberId", memberId));
//分组前先按时间倒序,这里划重点,排序必须在分页的前面,否则会导致排序只对当前页面有效
operations.add(Aggregation.sort(Sort.Direction.DESC, "createTime"));
//分组(去重) 使用mongoTemplate.findDistinct去重,不支持排序
operations.add(Aggregation.group("dynamicId").first("dynamicId").as("dynamicId").first("createTime").as("createTime"));
//分组后再按时间倒序一次
operations.add(Aggregation.sort(Sort.Direction.DESC, "createTime"));
//只取dynamicId字段
operations.add(Aggregation.project("dynamicId"));
//总数,划重点,分页必须在 总数统计 totalCount 的后面,否则会导致排序也只对当前页面有效
Long totalCount = repositoryOps.getTotalCount(operations, "comment", DynamicIdVO.class);
//分页参数
operations.add(Aggregation.skip((long) pagerVO.getPageMG() * pagerVO.getLimit()));
operations.add(Aggregation.limit(pagerVO.getLimit()));
}
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<DynamicIdVO> results = mongoTemplate.aggregate(aggregation, "comment", DynamicIdVO.class);