Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 310
Pete Montgomery Avatar asked Aug 26 '11 08:08

Pete Montgomery


People also ask

How do I find my local MongoDB URL?

connect('mongodb://localhost:27017/myapp'); This is the minimum needed to connect the myapp database running locally on the default port (27017). If connecting fails on your machine, try using 127.0. 0.1 instead of localhost .

What is the connection URL for MongoDB?

const MongoClient = require('mongodb'). MongoClient; const assert = require('assert'); // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Create a new MongoClient const client = new MongoClient(url); // Use connect method to connect to the Server client.


1 Answers

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 string var _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.

like image 189
Andrew Orsich Avatar answered Oct 01 '22 08:10

Andrew Orsich