springboot结合 mongodb 分页查询

mogngo分页简单快捷

@RequestMapping(value = "/page", method = RequestMethod.GET)
    public PageMessage selectSendRecord(HttpServletRequest request,long userId, String token, String moblie, long beginDate, long endDate, Integer status,
                                        @RequestParam(name = "page") Integer pageIndex, @RequestParam(name = "limit") Integer pageSize) {
          
   
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("user_id").is(userId);
        if (beginDate > 0 && endDate > 0) {
          
   
            query.addCriteria(Criteria.where("send_time").gte(beginDate).lte(endDate));
        }
        if (StringUtils.isNotBlank(moblie)) {
          
   
            //criteria.and("phone").is(moblie);
            criteria.and("phone").regex(moblie + ".*");
        }
        if (StringUtils.isNotBlank(status)) {
          
   
            criteria.and("status").is(status);
        }
        query.addCriteria(criteria);
        pageIndex = pageIndex - 1;
        if (pageIndex < 0) {
          
   
            pageIndex = 0;
        }
        int count = (int)mongoService.getMongoTemplate().count(query, User.class);
        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        query.with(pageable);
        query.with(Sort.by(Sort.Order.desc("user_id")));
        List<User> items = mongoService.getMongoTemplate().find(query, User.class);
        return new PageMessage (ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), count, items);
}

数据量大的话排序会出现下面的异常

com.mongodb.MongoQueryException: Query failed with error code 96 and error message ‘Executor error during find command :: caused by :: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.’ on server

主要原因是mongodb的sort操作是把数据拿到内存中再进行排序的,为了节约内存,默认给sort操作限制了最大内存为32Mb,当数据量越来越大直到超过32Mb的时候就自然抛出异常了。把索引建上就可以解决问题。

经验分享 程序员 微信小程序 职场和发展