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

I would like to connect to the database specified in the connection string, without specifying it again in GetDatabase.

For example, if I have a connection string like this;

mongodb://localhost/mydb

I would like to be able to db.GetCollection("mycollection") from mydb.

This would allow the database name to be configured easily in the app.config file.

This question is related to c# mongodb mongodb-.net-driver

The answer is


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");

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:[email protected],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");

The answer below is apparently obsolete now, but works with older drivers. See comments.

If you have the connection string you could also use MongoDatabase directly:

var db =  MongoDatabase.Create(connectionString);
var coll = db.GetCollection("MyCollection");