Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB specify database in connection string

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:[email protected]/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.

like image 410
Detilium Avatar asked Feb 17 '17 07:02

Detilium


1 Answers

In the connection string is possible to apply the option authSource.

Take this example: mongodb://admin:[email protected]/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);
}
like image 165
Detilium Avatar answered Oct 20 '22 20:10

Detilium