There are loads of SO's out there, but there one plain thing I don't understand, hence the creation of this SO.
Take the following connection string mongodb//admin:1234@10.0.125.1/my_database
. With this connection string, I would expect that I was able to connect to the MongoDB instance, and the specific database my_database
.
Following several SO's and othe rarticles, this should work, but if I look at the official documentation from MongoDB, the database
option is the database to which I want to authenticate.
/database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the “admin” database will be used by default.
I want my user to be authenticated towards the admin database (as that's where my user lies), but I want to access the database my_database
. I'd expect this procedure to work:
private static string _connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ToString();
public static IMongoDatabase GetDatabase()
{
var _url = MongoUrl.Create(_connectionString);
var _databaseName = _url.DatabaseName;
return new MongoClient(_connectionString).GetDatabase(_databaseName);
}
But whenever I do this, I'm receiving a timeout for any calls made to the MongoDB. An example is this:
public List<SomeObject> GetAllObjects()
{
var database = DatabaseInstance.GetDatabase();
// Error is thrown here (timout after 30000ms)
var objects = database.Getcollection<SomeObject>("SomeObjects").Find(Builders<SomeObject>.Filter.Empty).Find();
return objects;
}
Now, if I were to remove the database from the connection string and hard code the database name in my return new MongoClient(_connectionString).GetDatabase("my_database");
, everything works as expected.
This is where I don''t understand the /database option in the connection string. I'd really appreciate it if someone could shed some light on this.
In the connection string is possible to apply the option authSource
.
Take this example: mongodb://admin:1234@some.ip/my_database?authSource=admin
Now you should be able to get the current database name from the connection string, but authenticate towards the admin
database, using this code:
private static string _connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ToString();
public static IMongoDatabase GetDatabase()
{
var _databaseName = MongoUrl.Create(_connectionString).DatabaseName;
return new MongoClient(_connectionString).GetDatabase(_databaseName);
}