使用Java 連線MongoDB3.X 3.04 帶 auth 認證
阿新 • • 發佈:2019-02-06
/** * 測試MongoDB連線 */ private static void testMongoDBConn() { MongoClient client = null; try { // 使用者名稱 資料庫 密碼 MongoCredential credential = MongoCredential.createCredential("guoxin01", "guoxin", "123456".toCharArray()); //IP port ServerAddress addr = new ServerAddress("192.168.1.137", 27017); client = new MongoClient(addr,Arrays.asList(credential)); //得到資料庫 MongoDatabase mdb = client.getDatabase("guoxin"); //得到Table MongoCollection<?> table = mdb.getCollection("blog"); //查詢所有 FindIterable<?> fi = table.find(); //遍歷結果 for (Object o : fi) { System.out.println(o); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (client != null) { client.close(); } } }