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?