How to get Mongo database specified in connection string in C#
By Tan Lee Published on Nov 15, 2024 229
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);
Categories
Popular Posts
Horizon MUI Admin Dashboard Template
Nov 18, 2024
Elegent Material UI React Admin Dashboard Template
Nov 19, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024
Material Lite Admin Template
Nov 14, 2024