mongodb在Java中的分页查询

在gradle配置文件中引用

dependencies {
    compile(
            'org.mongodb:bson:3.4.2',
    	    'org.mongodb:mongo-java-driver:3.4.2'
    )
    testCompile('junit:junit:4.12')
}

1.在util类中定义公用静态单页查询和分页查询方法

/**
     * 单页查询,获取查询document结果集合
     * @param db  MongoDatabase
     * @param tableName 查询的表名
     * @param bson 查询条件
     * @param skip 忽略的条数
     * @param limit 查询的条数
     * @return document结果集合
     */
    public static List<Document> query(MongoDatabase db, String tableName, Bson bson, int skip, int limit) {
        List<Document> newLins = new ArrayList<>();
        Block<Document> saveBlock = new Block<Document>() {
            @Override
            public void apply(final Document document) {
                newLins.add(document);
            }
        };

        //查询
        MongoCollection<Document> collection = db.getCollection(tableName);

        collection.find(bson).skip(skip).limit(limit).forEach(saveBlock);

        return newLins;
    }

    /**
     * 分页查询
     * @param db  MongoDatabase
     * @param tableName 表名
     * @param bson 查询条件
     * @param pageSize 单页查询条数
     * @return 查询结果集合
     */
    public static List<Document> queryPages(MongoDatabase db, String tableName, Bson bson, int pageSize) {
        //分页查询
        List<Document> list = new ArrayList<>();
        long count = db.getCollection(tableName).count(bson);
        int loops = (int)((count + pageSize - 1) / pageSize);
        for(int i = 0; i < loops; i++) {
            List<Document> newFinds = query(db, tableName, bson, i * pageSize, pageSize);
            list.addAll(newFinds);
        }
        return list;
    }

2.在业务类中调用单页/分页查询

MongoDatabase mongoDatabase = Mongodb.getMongoDb().getDatabase("db_name");
            List<String> taskIds = new ArrayList<>();
            taskIds.add("123");
            taskIds.add("456");
            //bson就相当于where条件
            Bson bson = Filters.and(Filters.eq("status", 0),
                Filters.eq("dep", 1),
                Filters.in("taskId", taskIds));
            //查询tableName表中前1万条数据
            List<Document> myList = MonitorUtil.query(mongoDatabase, tableName, bson, 0, 10000);

上面是单页查询,下面是分页查询

Bson bsonLinks = Filters.and(
                    Filters.gt("lud", task_beginTime),
                    Filters.eq("rd", task_domain),
                    Filters.gte("dep", 2),
                    Filters.lte("dep",7));
                //分页查询
                List<Document> links = MonitorUtil.queryPages(mongoDatabase, tableName, bsonLinks, 1000);





评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值