Running a .NET Core API Locally with MongoDB

Running a .NET Core API Locally with MongoDB | Step-by-Step Guide

MongoDB is a popular NoSQL database that integrates seamlessly with .NET Core applications. Unlike relational databases, MongoDB stores data in flexible, JSON-like documents, making it ideal for modern web applications. This article will guide you through setting up and running a .NET Core API with MongoDB locally, covering:

  • Installing MongoDB and Compass GUI
  • Using MongoDB.Driver in .NET Core
  • Implementing CRUD operations with a NoSQL database

By the end of this tutorial, you will have a fully functional .NET Core API connected to MongoDB.


1. Installing MongoDB and Compass GUI

1.1 Download and Install MongoDB

MongoDB can be installed from the official website. Choose the appropriate version for your operating system and follow the installation instructions.

1.2 Start the MongoDB Service

Once installed, start MongoDB by running:

Windows:

mongod

macOS & Linux:

sudo systemctl start mongod

1.3 Install Compass GUI (Optional)

MongoDB Compass is a graphical interface that allows you to manage and visualize MongoDB data. Download it from MongoDB Compass.


2. Setting Up a .NET Core API with MongoDB

2.1 Create a New .NET Core Web API Project

Create a new Web API project using the .NET CLI:

dotnet new webapi -o MongoApi
cd MongoApi

2.2 Install MongoDB Driver for .NET

MongoDB provides an official MongoDB.Driver package for .NET applications. Install it via NuGet:

dotnet add package MongoDB.Driver

3. Implementing CRUD Operations with MongoDB

3.1 Configure MongoDB Connection

Modify appsettings.json to include MongoDB configuration:

{
  "MongoDB": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "MyDatabase"
  }
}

3.2 Create a MongoDB Service

Create a Services/MongoDbService.cs file:

using Microsoft.Extensions.Options;
using MongoDB.Driver;
using MongoApi.Models;

public class MongoDbService
{
    private readonly IMongoCollection<Item> _itemsCollection;
    
    public MongoDbService(IOptions<MongoDbSettings> settings)
    {
        var client = new MongoClient(settings.Value.ConnectionString);
        var database = client.GetDatabase(settings.Value.DatabaseName);
        _itemsCollection = database.GetCollection<Item>("Items");
    }

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

    public async Task<Item> GetAsync(string id) =>
        await _itemsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

    public async Task CreateAsync(Item item) =>
        await _itemsCollection.InsertOneAsync(item);

    public async Task UpdateAsync(string id, Item item) =>
        await _itemsCollection.ReplaceOneAsync(x => x.Id == id, item);

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

3.3 Define the Data Model

Create a Models/Item.cs file:

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

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

    public string Name { get; set; }
    public double Price { get; set; }
}

3.4 Implement API Controller

Modify Controllers/ItemsController.cs:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
    private readonly MongoDbService _mongoDbService;

    public ItemsController(MongoDbService mongoDbService)
    {
        _mongoDbService = mongoDbService;
    }

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

    [HttpGet("{id}")]
    public async Task<Item> Get(string id) => await _mongoDbService.GetAsync(id);

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

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(string id, Item item)
    {
        var existingItem = await _mongoDbService.GetAsync(id);
        if (existingItem is null) return NotFound();
        await _mongoDbService.UpdateAsync(id, item);
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        var item = await _mongoDbService.GetAsync(id);
        if (item is null) return NotFound();
        await _mongoDbService.RemoveAsync(id);
        return NoContent();
    }
}

4. Running the API and Testing with Postman

4.1 Start the API

Run the .NET API project:

dotnet run

4.2 Test the Endpoints with Postman

Use Postman or cURL to send HTTP requests:

  • GET All Items: GET http://localhost:5000/api/items
  • Get Item by ID: GET http://localhost:5000/api/items/{id}
  • Create New Item: POST http://localhost:5000/api/items (with JSON body)
  • Update Item: PUT http://localhost:5000/api/items/{id}
  • Delete Item: DELETE http://localhost:5000/api/items/{id}

Conclusion

We have successfully set up a .NET Core API that connects to MongoDB, covering:

  • Installing and running MongoDB locally
  • Configuring MongoDB.Driver for .NET Core
  • Implementing CRUD operations

With this knowledge, you can build scalable applications that leverage the flexibility of MongoDB as a NoSQL database. 🚀

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post