您好,登錄后才能下訂單哦!
public static void main(String[] args) {
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
// 與數據最大連接數50
build.connectionsPerHost(50);
// 如果當前所有的connection都在使用中,則每個connection上可以有50個線程排隊等待
build.threadsAllowedToBlockForConnectionMultiplier(50);
build.connectTimeout(1 * 60 * 1000);
build.maxWaitTime(2 * 60 * 1000);
MongoClientOptions options = build.build();
String host="192.168.80.100";
int port=27017;
MongoClient client = new MongoClient(new ServerAddress(host, port), options);
// 獲取數據庫test,不存在的話,會自動建立該數據庫
MongoDatabase db = client.getDatabase("fanyin");
// { storageEngine: {
// wiredTiger: { configString: 'block_compressor=zlib' }}
CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions();
BasicDBObject configString = new BasicDBObject();
configString.put("configString", "block_compressor=zlib");
BasicDBObject bson = new BasicDBObject();
bson.put("wiredTiger", configString);
createCollectionOptions.storageEngineOptions(bson);
boolean isCollectionExist=collectionExists(db, "data");
if(!isCollectionExist){
db.createCollection("data", createCollectionOptions);
}
MongoCollection<Document> users = db.getCollection("data");
for (int i = 0; i < 1; i++) {
Document document = new Document();
document.append("address2", "sichuan chengdu444444444444444444444444");
document.append("address3", "sichuan chengdu44455555555555555555555555555555");
users.insertOne(document);
}
MongoCollection<Document> users1 = db.getCollection("data1");
for (int i = 0; i < 1; i++) {
Document document = new Document();
document.append("address2", "sichuan chengdu444444444444444444444444");
document.append("address3", "sichuan chengdu44455555555555555555555555555555");
users1.insertOne(document);
}
// MongoClient使用完后必須要close釋放資源
client.close();
System.out.println("ooooooooooooookkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
}
//判斷collection是否存在
private static boolean collectionExists(MongoDatabase database,String collectionName){
final MongoIterable<String> iterable = database.listCollectionNames();
try (final MongoCursor<String> it = iterable.iterator()) {
while (it.hasNext()) {
if (it.next().equalsIgnoreCase(collectionName)) {
return true;
}
}
}
return false;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。