How to connect to MongoDB 3.2 in Java with username and password?
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