How to get the Mongo database specified in connection string in C# How to get the Mongo database specified in connection string in C# mongodb mongodb

How to get the Mongo database specified in connection string in C#


Update:

MongoServer.Create is obsolete now (thanks to @aknuds1). Instead this use following code:

var _server = new MongoClient(connectionString).GetServer();

It's easy. You should first take database name from connection string and then get database by name. Complete example:

var connectionString = "mongodb://localhost:27020/mydb";//take database name from connection stringvar _databaseName = MongoUrl.Create(connectionString).DatabaseName;var _server = MongoServer.Create(connectionString);//and then get database by database name:_server.GetDatabase(_databaseName);

Important: If your database and auth database are different, you can add a authSource= query parameter to specify a different auth database. (thank you to @chrisdrobison)

From docs:

NOTE If you are using the database segment as the initial database to use, but the username and password specified are defined in a different database, you can use the authSource option to specify the database in which the credential is defined. For example, mongodb://user:pass@hostname/db1?authSource=userDb would authenticate the credential against the userDb database instead of db1.


In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:

var connectionString = @"mongodb://usr:pwd@srv1.acme.net,srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";var mongoUrl = new MongoUrl(connectionString);var dbname = mongoUrl.DatabaseName;var db = new MongoClient(mongoUrl).GetDatabase(dbname);db.GetCollection<MyType>("myCollectionName");


With version 1.7 of the official 10gen driver, this is the current (non-obsolete) API:

const string uri = "mongodb://localhost/mydb";var client = new MongoClient(uri);var db = client.GetServer().GetDatabase(new MongoUrl(uri).DatabaseName);var collection = db.GetCollection("mycollection");