Java連接MongoDB


1.MongoDB沒有添加使用auth認證方式

MongoClientURI uri = new MongoClientURI("mongodb://192.168.32.129:27017/local",
               MongoClientOptions.builder().cursorFinalizerEnabled(false));
     MongoClient client = new MongoClient(uri);
     MongoDatabase db=client.getDatabase("local");
     MongoCollection<Document> collection = db.getCollection("system.users");
     List<Document> foundDocument = collection.find().into(new ArrayList<Document>());
     System.out.println(foundDocument);

2.MongoDB啟動的時候添加--auth參數啟動MongoDB(即安全認證模式下)

private static MongoClient mongoClient = null;
   private static MongoDatabase database = null;
   private static ServerAddress serverAddress = null;
   private static MongoCredential  credentials  = null;
   private static List<ServerAddress> addressLists =new ArrayList<ServerAddress>();
   private static List<MongoCredential> credentialsLists = new ArrayList<MongoCredential>();

try{
       //mongoClient = new MongoClient("192.168.32.129",27017);
       serverAddress = new ServerAddress("192.168.32.129",27017);
       addressLists.add(serverAddress);
       credentials = MongoCredential.createMongoCRCredential("admin", "admin", "admin".toCharArray());
       credentialsLists.add(credentials);
       mongoClient = new MongoClient(addressLists, credentialsLists);
       }catch (MongoException e)
       {
           System.out.println(e.toString());
       }
       if(null != mongoClient){
           database = mongoClient.getDatabase("admin");
           /* collection = database.getCollection("system.users");
           foundDocument = collection.find().into(
                    new ArrayList<Document>());
           System.out.println(foundDocument);*/
       }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM