How to connect to MongoDB 3.2 in Java with username and password?

前端 未结 2 1431
悲&欢浪女
悲&欢浪女 2020-12-30 13:37

I\'m using MongoDB 3.2 in my application. The code below demonstrates database initialization logic:

private void dbInit(String dbName) {

    String mongoCl         


        
相关标签:
2条回答
  • 2020-12-30 13:54

    As MarkusWMahlberg correctly noted, it is necessary to note the database name in the connection string.

    For instance:

    String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;
    
    0 讨论(0)
  • 2020-12-30 13:58

    Tested with mongodb-3.4.2 and mongo-java-driver-3.4.2.jar

    (1) Use MongoCredential

    MongoCredential credential = MongoCredential.createCredential("user", "database", "passwd".toCharArray());
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential));
    MongoDatabase db = mongoClient.getDatabase( "test" );
    MongoCollection collection = db.getCollection("mycol");
    FindIterable fi = collection.find();
    MongoCursor cursor = fi.iterator();
    

    (2) Use MongoClientURI

    MongoClientURI uri = new MongoClientURI("mongodb://user:passwd@localhost:27017/?authSource=test");
    MongoClient mongoClient = new MongoClient(uri);
    

    There are some variant forms for using MongoCredential and MongoClientURI for different authentication mechanisms, check here for details

    0 讨论(0)
提交回复
热议问题