I\'m using MongoDB 3.2 in my application. The code below demonstrates database initialization logic:
private void dbInit(String dbName) {
String mongoCl
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;
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