在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 Listquery(MongoDatabase db, String tableName, Bson bson, int skip, int limit) {
ListnewLins = new ArrayList<>();
BlocksaveBlock = new Block() {
@Override
public void apply(final Document document) {
newLins.add(document);
}
};
//查询
MongoCollectioncollection = 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 ListqueryPages(MongoDatabase db, String tableName, Bson bson, int pageSize) {
//分页查询
Listlist = new ArrayList<>();
long count = db.getCollection(tableName).count(bson);
int loops = (int)((count + pageSize - 1) / pageSize);
for(int i = 0; i < loops; i++) {
ListnewFinds = query(db, tableName, bson, i * pageSize, pageSize);
list.addAll(newFinds);
}
return list;
}
2.在业务类中调用单页/分页查询
MongoDatabase mongoDatabase = Mongodb.getMongoDb().getDatabase("db_name");
ListtaskIds = 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万条数据
ListmyList = 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));
//分页查询
Listlinks = MonitorUtil.queryPages(mongoDatabase, tableName, bsonLinks, 1000);