mongoDB 分页

  Criteria criteria = new Criteria();
       /* 暂无条件
       if (StringUtils.isNotBlank(phone)) {
            criteria.orOperator(Criteria.where("phone").is(phone)
                    , Criteria.where("result.jd_protype_data.self_phone_list").elemMatch(Criteria.where("phone").is(phone))
                    , Criteria.where("result.jd_protype_data.consignee_jd_contact_list").elemMatch(Criteria.where("phone").is(phone)));
        }*/
        Query query = new Query(criteria);
        //mongoTemplate.count计算总数
        long total = mongoTemplate.count(query, interfaceName);
 //总页数
 
            long totalPageNum = (total + pageSize - 1) / pageSize;
            String mid = "";
            for (int i = 1; i <= totalPageNum; i++) {
                log.info("---------------第" + i + "页----------------");
                Set<String> set = new HashSet<String>();
                try {
                    BasicDBObject totalCon = new BasicDBObject();
                    if (StringUtils.isNotBlank(mid)) {
                        totalCon.put("_id", new BasicDBObject("$gt", new ObjectId(mid)));
                    }
                    DBCursor dbObjects = getPageList(pageSize, interfaceName, totalCon);
                    while (dbObjects.hasNext()) {
                        DBObject dbObject = dbObjects.next();
                        //log.error(  dbObject.toString());
                        String str = dbObject.toString();
                        getPhoneStr(str, set);
                        mid = dbObject.get("_id").toString();
                    }
                    getMemberList(set);

                } catch (Exception e) {
                    log.info("mongoDB爆炸了,查询异常");
                    log.info("异常信息:{}", e);
                    e.printStackTrace();
                }
            }
   /**
     * 大数据量排序方式分页获取数据
     *
     * @param collectionName 表名
     * @param totalCon       查询条件汇总
     */
    public DBCursor getPageList(int pageSize, String collectionName, BasicDBObject totalCon) {
        try {
            return mongoTemplate.getCollection(collectionName).find(totalCon).sort(new BasicDBObject("_id", 1)).limit(pageSize);
        } catch (Exception e) {
            log.error("***大数据量数据分页查询失败,collectionName=" + collectionName, e);
        }
        return null;
    }

你可能感兴趣的:(mongoDB)