How to connect to MongoDB in C#
By FoxLearn 11/15/2024 4:34:01 AM 35
How to connect to MongoDB via the .Net driver?
The first thing you'll need to do is install the MongoDB driver for .NET in your project. You can do this via NuGet.
Open your package manager console in Visual Studio, then run the following command to install the MongoDB driver:
Install-Package MongoDB.Driver
Once the driver is installed, you can use the MongoClient
class to connect to your MongoDB instance.
To access your MongoDB database directly from the MongoClient
, you can use the GetDatabase
method, which allows you to retrieve a specific database by its name.
string connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var database = client.GetDatabase("myDatabase"); // Access "myDatabase"
MongoClient: This is the main entry point to interact with MongoDB. The connection string is passed to it to establish a connection to the MongoDB server.
GetDatabase: You can access a specific database using the GetDatabase()
method. If the database doesn't exist, MongoDB will create it for you when you add collections and documents.
If MongoDB is running with authentication enabled:
mongodb://username:password@localhost:27017
This gives you direct access to the database, where you can perform operations like accessing collections, querying documents, etc.