How to use MongoDB in your .NET Core Application

Intro

MongoDB is an open-source, document-oriented NoSQL database system that stores data in collections and documents. It uses dynamic schemas, which makes it easier to store and query data than traditional relational databases. MongoDB is a popular choice for modern web applications due to its scalability, high performance, and flexibility. With its easy-to-use interface and powerful features, MongoDB can help you create dynamic web applications quickly and easily.


Before going further, if you don't have a prepared MongoDB instance, you can create and manage a free hosted serverless MongoDB cluster on their website - visit this topic for more information.



Integrate MongoDB NuGet packages in your application

Firstly, in order to connect and consume a MongoDB connection - the core packages needs to be integrated into your project.


Install MongoDB Driver NuGet Package



Prepare your entities for storing data into collections

Going further, models must pe implemented and declared as instructed on the project documentation. The following example will be used in order to store simple categories in a Category collection in our MongoDB cluster.


public class Category
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }
    public string Name { get; set; } = null!;
    public string Description { get; set; } = null!;
}



MongoDB client - Interface

A MongoDB client interface is being created in order to use it through the entire project using the dependency injection design pattern.


public interface IMongoDBClient
{
    Task<IEnumerable<Category>> GetCategoriesAsync();
    Task<Category> GetCategoryAsync(string id);
    Task CreateCategoryAsync(Category category);
    Task UpdateCategoryAsync(Category category);
}



MongoDB client - Implementation

The actual implementation of the previously created interface where all the logic for MongoDB usage is placed and ready to go.

Sensitive data like connection strings are coming through a dynamic configuration provider, which can be either the local application settings file or a 3rd party secure secret storage. For security purposes, we advice everyone to store sensitive data in places with enhanced involvement in security like Azure Key Vault.


public class MongoDBClient : IMongoDBClient
{
    private readonly IMongoCollection<Category> _categoryCollection;

    public MongoDBClient(IConfiguration configuration)
    {
        MongoClient client = new MongoClient(configuration["MongoDBConnectionURI"]);
        IMongoDatabase database = client.GetDatabase(configuration["MongoDBDatabaseName"]);

        _categoryCollection = database.GetCollection<Category>(nameof(Category));
    }

    public async Task<IEnumerable<Category>> GetCategoriesAsync()
    {
        return await _categoryCollection.Find(_ => true).ToListAsync();
    }

    public async Task<Category> GetCategoryAsync(string id)
    {
        return await _categoryCollection.Find(x => x.Id == id).FirstOrDefaultAsync();
    }

    public async Task CreateCategoryAsync(Category category)
    {
        await _categoryCollection.InsertOneAsync(category);
    }

    public async Task UpdateCategoryAsync(Category category)
    {
        await _categoryCollection.ReplaceOneAsync(x => x.Id == category.Id, category);
    }
}



Special remarks

Based on MongoDB project documentation, the usage of their client is thread safe and because of this, the client will be used as a singleton across the project. For Web based .NET Core applications, this is an example of registering the previously created client as a singleton to be used further with the magic of dependency injection.


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IMongoDBClient, MongoDBClient>();



Conclusions

MongoDB is a very cool NoSQL database which lets you create dynamic collections containing your project entities with no further configurations, being a powerful quick start for any type of project.