Testet med mongodb-3.4.2 og mongo-java-driver-3.4.2.jar
(1) Brug 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) Brug MongoClientURI
MongoClientURI uri = new MongoClientURI("mongodb://user:[email protected]:27017/?authSource=test");
MongoClient mongoClient = new MongoClient(uri);
Der er nogle varianter til brug af MongoCredential og MongoClientURI til forskellige godkendelsesmekanismer, tjek her for detaljer