mongodb分页
基于SpringBoot中的mongoTemplate实现
工具类:
package com.cf.common; import com.github.pagehelper.PageInfo; import org.springframework.data.mongodb.core.query.Query; /** * Mongo分页封装 * * @author jxd * @version 1.0 * * @date 2020/11/11 10:51 */ public class MongoPageUtil { /** * 分页处理 * * @return * @author jxd * @date 2020/11/11 12:00 */ public static void wrapPageQuery(Query query, Integer currentPage, Integer pageSize) { query.skip((currentPage - 1) * pageSize); query.limit(pageSize); } /** * 包装返回结果 * * @param pageInfo * @param totalSize * @param currentPage * @param pageSize * @return * @author jxd * @date 2020/11/11 12:15 */ public static void wrapPageInfo(PageInfo pageInfo, Integer totalSize, Integer currentPage, Integer pageSize) { long pages = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1L; pageInfo.setPages((int) pages); pageInfo.setTotal(totalSize); pageInfo.setPageSize(pageSize); pageInfo.setPageNum(currentPage); } }
应用:
@Override public PageInfo queryList(RedemptionCodeRecordDto redemptionCodeRecordDto) { Query query = new Query(); Set<String> parmas = new HashSet<>(); renderParamasSet(parmas); JSONObject redemptionCodeRecordDtoJson = (JSONObject) JSONObject.toJSON(redemptionCodeRecordDto); parmas.forEach(x -> { String v = redemptionCodeRecordDtoJson.getString(x); if (StringUtils.isNotBlank(v)) { query.addCriteria(Criteria.where(x).is(v)); } });
//按插入时间倒序 query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "redemptionDate"))); Integer currentPage = redemptionCodeRecordDto.getCurrentPage(); Integer pageSize = redemptionCodeRecordDto.getPageSize(); MongoPageUtil.wrapPageQuery(query, currentPage, pageSize); long total = centerMongoTemplate.count(query, RedemptionCodeRecordDto.class, redemtionCodeRecord); List<RedemptionCodeRecordDto> list = centerMongoTemplate.find(query, RedemptionCodeRecordDto.class, redemtionCodeRecord); for (RedemptionCodeRecordDto codeRecordDto : list) { codeRecordDto.setRedemptionStatus(CommonEnum.renderRedemptionStatus(codeRecordDto.getRedemptionStatus())); } PageInfo pageInfo = new PageInfo(list); MongoPageUtil.wrapPageInfo(pageInfo, (int) total, currentPage, pageSize); return pageInfo; }