I am trying to create a generic mongo connection component that will be used with different mongo DB instances. I managed to make it work with some code like:
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// Accessing the database
MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
I don't understand why it needs to specify the database in 2 places: "myDb", once in the credential, and once while it does a getDatabase. More than that on my setup I need to specify a different DB on createCredential: "admin" in order to work. Why is the credential database different than the one I will run the query?
When you inspect the code deeper, you will find the below compelling reasons.
This is the place where all the authenticators falls down.
authenticatorscontains list of credentials. There are four implementations.Main reason to specify here, on which database the authenticate command has to be executed as each database can have different user name.
It is altogether different. It returns
MongoDatabaseobject which contains options toread, write concerns, list of collections, create view, create collection.