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

By FoxLearn 11/15/2024 4:08:58 AM   30
To get the MongoDB database specified in the connection string in C#, you can use the MongoDB .NET driver.

If you haven't already, you need to install the MongoDB .NET driver:

Package Manager. PM > Install-Package MongoDB.Driver

MongoDB connection strings typically have this format:

mongodb://<username>:<password>@<host>:<port>/<database>?options

You can use the MongoClient class to connect to the server and specify the database.

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

It's straightforward to retrieve a MongoDB database from a connection string in C#.

First, extract the database name from the connection string, then use it to access the database.

var connectionString = "mongodb://localhost:27020/mydb";

// Extract the database name from the connection string
var databaseName = MongoUrl.Create(connectionString).DatabaseName;
var server = MongoServer.Create(connectionString);

//and then get database by database name:
server.GetDatabase(_databaseName);