Even though it is common to use ASP.NET Core with SQL Databases, there are some cases where a NoSQL database would come in handy. In this tutorial, we’re going to go over how to add MongoDB support to your ASP.NET Core Rest API. Also, please watch the video tutorials here to get a visual representation of how this is implemented.

Setup

For this tutorial, we’ll be using Jetbrains Rider but you can also use the CLI to generate your project if you prefer.

Jetbrains Rider Startup

Next, you can use the CLI to add the MongoDB Driver.

dotnet add BooksApi.csproj package MongoDB.Driver

Rider also has the option of adding Dependencies using the Package Manager.

Rider Package Manager

In order to connect our ASP.NET Core Application with a MongoDB database, we’re going to have to configure the connection. First we must add the MongoDB Settings to our appsettings.json file.

{
  "TodosDatabaseSettings": {
    "TodosCollectionName": "Todos",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "TodosDB"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

We’ll also create a settings model for our DB configuration to serialize the config into our app.

namespace MongoDBExample.Models
{
    public class TodosDatabaseSettings : ITodosDatabaseSettings
    {
        public string TodosCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface ITodosDatabaseSettings
    {
        string TodosCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }
}

Now inside of our ConfigureServices method in our StartUp file, we will add those configurations.

        public void ConfigureServices(IServiceCollection services)
        {
            // requires using Microsoft.Extensions.Options
            services.Configure<TodosDatabaseSettings>(
                Configuration.GetSection(nameof(TodosDatabaseSettings)));

            services.AddSingleton<ITodosDatabaseSettings>(sp =>
                sp.GetRequiredService<IOptions<TodosDatabaseSettings>>().Value);
            services.AddControllers();
        }

Repository Design

First we need to create a Todo model to represent out objects in our DB collection.

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

namespace MongoDBExample.Models
{
    public class Todo
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        
        public string Title { get; set; }

        public bool Complete { get; set; }
    }
}

In order to use our DB configuration in the application, we’ll create a Repository to handle all of our CRUD operations.

using System.Collections.Generic;
using MongoDB.Driver;

namespace MongoDBExample.Models
{
    public class TodosRepository
    {
        public class BookService
        {
            private readonly IMongoCollection<Todo> _todos;

            public BookService(ITodosDatabaseSettings settings)
            {
                var client = new MongoClient(settings.ConnectionString);
                var database = client.GetDatabase(settings.DatabaseName);

                _todos = database.GetCollection<Todo>(settings.TodosCollectionName);
            }

            public List<Todo> Get() =>
                _todos.Find(book => true).ToList();

            public Todo Get(string id) =>
                _todos.Find<Todo>(book => book.Id == id).FirstOrDefault();

            public Todo Create(Todo todo)
            {
                _todos.InsertOne(todo);
                return todo;
            }

            public void Update(string id, Todo todo) =>
                _todos.ReplaceOne(todo => todo.Id == id, todo);

            public void Remove(Todo todo) =>
                _todos.DeleteOne(todo => todo.Id == todo.Id);

            public void Remove(string id) => 
                _todos.DeleteOne(todo => todo.Id == id);
        }
    }
}

This repository gets our Connection Settings and creates a MongoDB connection from it. We then add the repository as a singleton.

services.AddSingleton<TodosRepository>();

Adding the Controller

Next we’ll add our controller that implements our repository.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using MongoDBExample.Models;

namespace MongoDBExample.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodosController : ControllerBase
    {
        private readonly TodosRepository _todosRepository;

        public TodosController(TodosRepository todosRepository)
        {
            _todosRepository = todosRepository;
        }

        [HttpGet]
        public ActionResult<List<Todo>> Get() =>
            _todosRepository.Get();

        [HttpGet("{id:length(24)}", Name = "GetTodo")]
        public ActionResult<Todo> Get(string id)
        {
            var todo = _todosRepository.Get(id);

            if (todo == null)
            {
                return NotFound();
            }

            return todo;
        }

        [HttpPost]
        public ActionResult<Todo> Create(Todo todo)
        {
            _todosRepository.Create(todo);

            return CreatedAtRoute("GetTodo", new { id = todo.Id.ToString() }, todo);
        }

        [HttpPut("{id:length(24)}")]
        public IActionResult Update(string id, Todo todoIn)
        {
            var todo = _todosRepository.Get(id);

            if (todo == null)
            {
                return NotFound();
            }

            _todosRepository.Update(id, todoIn);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            var todo = _todosRepository.Get(id);

            if (todo == null)
            {
                return NotFound();
            }

            _todosRepository.Remove(todo.Id);

            return NoContent();
        }
    }
}

Now if we make the respective GET and POST requests, we’ll see our data is persisted to the DB.

Mongo Get Request ASP.NET Core
MongoDB Post Request ASP.NET Core

Conclusion

This tutorial went over a basic example of how to add MongoDB to an ASP.NET Core Rest API. If you’re interested in learning more, please join on community and get access to tons of video tutorials.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit