Testováno s mongodb-3.4.2 a mongo-java-driver-3.4.2.jar
(1) Použijte 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) Použijte MongoClientURI
MongoClientURI uri = new MongoClientURI("mongodb://user:[email protected]:27017/?authSource=test");
MongoClient mongoClient = new MongoClient(uri);
Existuje několik variant formulářů pro použití MongoCredential a MongoClientURI pro různé mechanismy ověřování, zkontrolujte zde podrobnosti