1. 程式人生 > >mongoDB 分頁

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;
    }