Implement MongoDB in .NET Core: Step-by-Step Guide


Modern applications require flexible and scalable databases to handle large amounts of structured and unstructured data. While SQL databases are excellent for relational data, NoSQL databases like MongoDB provide greater flexibility and horizontal scalability.

What is MongoDB?

MongoDB is an open-source, document-oriented NoSQL database that stores data in JSON-like documents called BSON (Binary JSON). Unlike traditional relational databases, MongoDB doesn't require a fixed schema, making it ideal for applications with rapidly changing requirements.

Benefits of MongoDB

  • Schema-less database design
  • High scalability and performance
  • Easy integration with cloud applications
  • Flexible document model
  • Supports large volumes of data

Prerequisites

Before starting, make sure you have the following installed:

  • .NET 8 SDK or .NET 7 SDK
  • MongoDB Community Server
  • Visual Studio 2022 or Visual Studio Code
  • Basic knowledge of ASP.NET Core Web API

Step 1: Create a New ASP.NET Core Web API Project

Open the terminal and execute:

dotnet new webapi -n MongoDbDemo
cd MongoDbDemo

Run the application:

dotnet run

Step 2: Install MongoDB Driver

Install the official MongoDB package using NuGet:

dotnet add package MongoDB.Driver

Or use the Package Manager Console:

Install-Package MongoDB.Driver

Step 3: Configure MongoDB Settings

Create a folder named Configurations and add a class named MongoDbSettings.cs.

public class MongoDbSettings
{
    public string ConnectionString { get; set; } = null!;
    public string DatabaseName { get; set; } = null!;
    public string CollectionName { get; set; } = null!;
}

Step 4: Add Configuration in appsettings.json

{
  "MongoDbSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "EmployeeDb",
    "CollectionName": "Employees"
  }
}

Step 5: Create the Model

Create a Models folder and add Employee.cs.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Employee
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }

    public string Name { get; set; } = string.Empty;

    public string Department { get; set; } = string.Empty;

    public decimal Salary { get; set; }
}

Step 6: Create MongoDB Service

Create a Services folder and add EmployeeService.cs.

using MongoDB.Driver;

public class EmployeeService
{
    private readonly IMongoCollection<Employee> _employees;

    public EmployeeService(IOptions<MongoDbSettings> settings)
    {
        var mongoClient = new MongoClient(
            settings.Value.ConnectionString);

        var mongoDatabase = mongoClient.GetDatabase(
            settings.Value.DatabaseName);

        _employees = mongoDatabase.GetCollection<Employee>(
            settings.Value.CollectionName);
    }

    public async Task<List<Employee>> GetAsync() =>
        await _employees.Find(_ => true).ToListAsync();

    public async Task<Employee?> GetAsync(string id) =>
        await _employees.Find(x => x.Id == id)
                        .FirstOrDefaultAsync();

    public async Task CreateAsync(Employee employee) =>
        await _employees.InsertOneAsync(employee);

    public async Task UpdateAsync(string id, Employee employee) =>
        await _employees.ReplaceOneAsync(x => x.Id == id, employee);

    public async Task DeleteAsync(string id) =>
        await _employees.DeleteOneAsync(x => x.Id == id);
}

Step 7: Register Services in Program.cs

builder.Services.Configure<MongoDbSettings>(
    builder.Configuration.GetSection("MongoDbSettings"));

builder.Services.AddSingleton<EmployeeService>();

Step 8: Create API Controller

Create EmployeesController.cs.

[ApiController]
[Route("api/[controller]")]
public class EmployeesController : ControllerBase
{
    private readonly EmployeeService _employeeService;

    public EmployeesController(EmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    [HttpGet]
    public async Task<List<Employee>> Get() =>
        await _employeeService.GetAsync();

    [HttpGet("{id}")]
    public async Task<ActionResult<Employee>> Get(string id)
    {
        var employee = await _employeeService.GetAsync(id);

        if (employee is null)
            return NotFound();

        return employee;
    }

    [HttpPost]
    public async Task<IActionResult> Post(Employee employee)
    {
        await _employeeService.CreateAsync(employee);
        return CreatedAtAction(nameof(Get),
            new { id = employee.Id },
            employee);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(
        string id,
        Employee employee)
    {
        await _employeeService.UpdateAsync(id, employee);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        await _employeeService.DeleteAsync(id);
        return NoContent();
    }
}

Step 9: Run the Application

Execute:

dotnet run

Open Swagger:

https://localhost:5001/swagger

You can now perform:

  • GET all employees
  • GET employee by ID
  • POST new employee
  • PUT update employee
  • DELETE employee

Testing the API

Create Employee

{
  "name": "John Doe",
  "department": "IT",
  "salary": 50000
}

Response

{
  "id": "6656d7a31c74f19f1d55d001",
  "name": "John Doe",
  "department": "IT",
  "salary": 50000
}

Advantages of Using MongoDB with .NET Core

  • High performance for large datasets.
  • Flexible schema design.
  • Easy integration using MongoDB.Driver.
  • Excellent support for microservices architecture.
  • Suitable for cloud-native applications.

Best Practices

  • Use Dependency Injection.
  • Store connection strings in configuration files.
  • Implement Repository Pattern for large applications.
  • Add proper exception handling.
  • Use indexes for better query performance.
  • Implement pagination for large collections.
  • Secure MongoDB with authentication.

Conclusion

MongoDB and .NET Core make an excellent combination for building scalable, high-performance applications. By following the steps in this tutorial, you can easily integrate MongoDB into your ASP.NET Core Web API and implement complete CRUD operations.

As your application grows, you can further enhance it by implementing Repository Pattern, Generic Services, Authentication, and advanced MongoDB features such as Aggregation Pipelines and Transactions.

0 Comments Report