Java使用MongoTemplate分页查询MongoDB

Java使用MongoTemplate分页查询MongoDB,如有问题请指正。


    org.springframework.boot
    spring-boot-starter-data-mongodb
    
        
            org.mongodb
            mongodb-driver
        
    

如果是MongoDB最新版本则需要改变 spring boot 版本 否则会出现版本兼容问题,如下图:

Java使用MongoTemplate分页查询MongoDB_第1张图片

具体实现:

@Autowired
private MongoTemplate mongoTemplate;

/**
 * 根据条件分页获取请求日志信息
 *
 * @param pageIndex
 * @param pageSize
 * @param sTime
 * @param eTime
 * @param address
 * @return
 * @throws Exception
 */
@Override
public PageModel findLogPage(Integer pageIndex, Integer pageSize,
                                             String sTime, String eTime, String address) throws Exception {

    PageModel pageable = new PageModel();
    List logList = new ArrayList();
    if (null == pageIndex || pageIndex == 0) {
        pageIndex = 1;
    }
    if (null == pageSize || pageSize == null) {
        pageSize = 10;
    }
    try {
        List operations = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (null != sTime && !sTime.equals("")) {
            Criteria criteria = Criteria.where("requestTime").gt(formatter.parse(sTime));
            operations.add(Aggregation.match(criteria));
        }
        if (null != eTime && !eTime.equals("")) {
            Criteria criteria = Criteria.where("requestTime").lt(formatter.parse(eTime));
            operations.add(Aggregation.match(criteria));
        }
        if (null != address && !address.equals("")) {
            Criteria criteria = Criteria.where("url").regex(address);
            operations.add(Aggregation.match(criteria));
        }
        //使用skip 跳过数据,如果数据量庞大则影响性能问题
        operations.add(Aggregation.skip((long) (pageIndex - 1) * pageSize));
        operations.add(Aggregation.limit(pageSize));
        operations.add(Aggregation.lookup("doc_category", "categoryCode", "code", "category"));
        operations.add(Aggregation.sort(Sort.Direction.DESC, "requestTime"));
        //operations.add(Aggregation.group("requestTime","url","requestNo","responseBody")); 指定返回字段
        Aggregation aggregation = Aggregation.newAggregation(operations);
        AggregationResults results = mongoTemplate.aggregate(
            aggregation, "httpInboundLog", HttpInboundLog.class);
        logList = results.getMappedResults();
        pageable.setPageSize(pageSize);
        pageable.setRow(this.findLogCount(sTime,eTime,address));//查询出符合条件总数
        pageable.setResult(logList);
        return pageable;
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("code:500------msg:分页查询MongoDB中请求日志失败");
        throw new RuntimeErrorCode(500, "分页查询MongoDB中请求日志失败");
    }
}

/**
 * 查询符合条件总条数
 * @param sTime
 * @param eTime
 * @param address
 * @return
 * @throws Exception
 */
public long findLogCount(String sTime, String eTime, String address) throws Exception {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Query query = new Query();
    if (null != sTime && !sTime.equals("")) {
        Criteria criteria = Criteria.where("requestTime").gt(formatter.parse(sTime));
        query.addCriteria(criteria);
    }
    if (null != eTime && !eTime.equals("")) {
        Criteria criteria = Criteria.where("requestTime").lt(formatter.parse(eTime));
        query.addCriteria(criteria);
    }
    if (null != address && !address.equals("")) {
        Criteria criteria = Criteria.where("url").regex(address);
        query.addCriteria(criteria);
    }
    long count = mongoTemplate.count(query, HttpInboundLog.class);


    return count;
}

pagemodel 封装类

@Data
public class PageModel<T> {
    private int pageIndex;//当前页
    private long row;//记录数
    private int pageSize;//每页显示条数
    private List<T> result;//结果集

    /**
     * 获取总页数
     *
     * @return
     */
    public int getPages() {
        return ((int) row + pageSize - 1) / pageSize;
    }
    /**
     * 取得首页
     * @return
     */
    public int getTopPageNo(){
        return 1;
    }
    /**
     * 上一页
     * @return
     */
    public int getPreviousPageNo(){
        if(pageIndex<=1){
            return 1;
        }
        return pageIndex-1;
    }
    /**
     * 下一页
     * @return
     */
    public int getNextPageNo(){
        if(pageIndex>=getBottomPageNo()){
            return getBottomPageNo();
        }
        return pageIndex+1;
    }
    /**
     * 取得尾页
     * @return
     */
    public int getBottomPageNo(){
        return getPages();
    }


转载请注明出处。。。。。。



你可能感兴趣的:(MongoDB)