How to get Mongo database specified in connection string in C#
By Tan Lee Published on Nov 15, 2024 256
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
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Modular Admin Template
Nov 14, 2024
How to secure ASP.NET Core with NWebSec
Nov 07, 2024
Login SignUp form using HTML CSS JS
Nov 11, 2024