MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. The C# driver for MongoDB allows developers to interact with MongoDB databases using the .NET framework. This tutorial will cover how to install and use the C# driver, including connecting to a MongoDB instance, performing CRUD operations, and handling exceptions.
Before you begin, ensure that you have the following:
The C# driver for MongoDB can be installed via NuGet. Open your project in Visual Studio, right-click on the project in the Solution Explorer, select "Manage NuGet Packages," and search for MongoDB.Driver. Install the latest stable version.
Alternatively, you can install it using the Package Manager Console:
Install-Package MongoDB.Driver
Or via the .NET CLI:
dotnet add package MongoDB.Driver
To connect to a MongoDB instance, you need to create a MongoClient object. This object represents a connection pool to the MongoDB server.
using MongoDB.Driver;
using System.Threading.Tasks;
public class MongoClientExample
{
private readonly IMongoClient _client;
private readonly IMongoDatabase _database;
public MongoClientExample(string connectionString, string databaseName)
{
_client = new MongoClient(connectionString);
_database = _client.GetDatabase(databaseName);
}
public async Task ConnectAsync()
{
try
{
// Ping the server to check if it's reachable
await _client.ListDatabasesAsync();
Console.WriteLine("Connected successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
}
}
}
CRUD operations (Create, Read, Update, Delete) are fundamental when working with any database. Below are examples of how to perform these operations using the C# driver.
To insert a document into a collection, use the InsertOneAsync or InsertManyAsync methods.
using MongoDB.Bson;
using MongoDB.Driver;
public class DocumentCreator
{
private readonly IMongoCollection<BsonDocument> _collection;
public DocumentCreator(IMongoDatabase database, string collectionName)
{
_collection = database.GetCollection<BsonDocument>(collectionName);
}
public async Task InsertDocumentAsync(BsonDocument document)
{
await _collection.InsertOneAsync(document);
Console.WriteLine("Document inserted successfully.");
}
}
To read documents from a collection, use the Find method.
public class DocumentReader
{
private readonly IMongoCollection<BsonDocument> _collection;
public DocumentReader(IMongoDatabase database, string collectionName)
{
_collection = database.GetCollection<BsonDocument>(collectionName);
}
public async Task ReadDocumentsAsync()
{
var filter = Builders<BsonDocument>.Filter.Empty;
var documents = await _collection.Find(filter).ToListAsync();
foreach (var document in documents)
{
Console.WriteLine(document.ToJson());
}
}
}
To update a document, use the UpdateOneAsync or UpdateManyAsync methods.
public class DocumentUpdater
{
private readonly IMongoCollection<BsonDocument> _collection;
public DocumentUpdater(IMongoDatabase database, string collectionName)
{
_collection = database.GetCollection<BsonDocument>(collectionName);
}
public async Task UpdateDocumentAsync(BsonDocument filter, BsonDocument update)
{
await _collection.UpdateOneAsync(filter, update);
Console.WriteLine("Document updated successfully.");
}
}
To delete a document, use the DeleteOneAsync or DeleteManyAsync methods.
public class DocumentDeleter
{
private readonly IMongoCollection<BsonDocument> _collection;
public DocumentDeleter(IMongoDatabase database, string collectionName)
{
_collection = database.GetCollection<BsonDocument>(collectionName);
}
public async Task DeleteDocumentAsync(BsonDocument filter)
{
await _collection.DeleteOneAsync(filter);
Console.WriteLine("Document deleted successfully.");
}
}
It's important to handle exceptions properly when working with databases. MongoDB operations can fail due to network issues, authentication errors, or invalid queries.
try
{
// Perform database operation here
}
catch (MongoConnectionException ex)
{
Console.WriteLine($"Connection error: {ex.Message}");
}
catch (MongoCommandException ex)
{
Console.WriteLine($"Command error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General error: {ex.Message}");
}
Async) to avoid blocking the main thread, especially in web applications.MongoClient is designed to be long-lived and reused across your application. Avoid creating a new MongoClient instance for each operation.The C# driver for MongoDB provides a powerful way to interact with MongoDB databases using the .NET framework. By following this tutorial, you should have a solid understanding of how to connect to MongoDB, perform CRUD operations, and handle exceptions. Remember to apply best practices to ensure efficient and secure database interactions.