在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);