Using MongoDB With ASP.NET Core Web API

Introduction

 
A common thing we hear in all places these days is NoSQL databases. These are being very strongly promoted by all vendors. One of the most common NoSQL databases these days is MongoDB. In this article we will discuss what a NoSQL database is, when it must be used and then we will look at an example to install, create and populate this database. Finally, we will look at how to access data from this database using a ASP.NET Core Web API.
 

What is a NoSQL database?

 
So, what exactly is a NoSQL database? It is a collection of documents with no real defined structure as in an RDBMS or SQL database. That means that we do not have any pre-defined columns as we do have in a SQL table. We simply store each row with its own number of columns or data fields as we may call them. Hence, we have a large store of documents (similar to rows in a SQL database with no predefined structure) organized into a collection (similar to tables in a SQL database) which are inside a database (similar to a database in a SQL database). So, what is the advantage of a NoSQL database? Well, for one, the data for each document is in one place and faster to read. Secondly, as there is no pre-defined structure we can store documents with different fields in one place and do not have to worry about adding new columns each time where most rows could contain NULLS as in a SQL database. Also, it saves us from creating new tables with relationships.
 

What is MongoDB?

 
MongoDB is one of the most common NoSQL databases out there from MongoDB Inc. Being a Microsoft developer, another well known NoSQL database is Cosmos DB in addition to the tables storage mechanism in Microsoft Azure. MongoDB can be downloaded and run from your desktop computer. It runs as a service. It also comes with a client called “MongoDB Compass Community”. This is a nice compact client which allows you to connect to the instance running, view the databases, collections, and documents inside it. It also allows you to create new databases, new collections inside the database, and new documents inside the collection using the JSON format. There are also other clients that you can use with the MongoDB server like Studio 3T etc.
 

Installing MongoDB and creating the database elements

 
The first step would be to download and install the MongoDB Server and Client. You can do this from the below URL:
https://www.mongodb.com/download-center/community
 
Once you have downloaded the MSI package, you can install it as shown below:
 
Using MongoDB With ASP.NET Core Web API
 
Remember to install the “MongoDB Compass Community” client as well. Once, the installation is complete, you can confirm that the service for MongoDB is running as shown below:
 
Using MongoDB With ASP.NET Core Web API
We now open the client and see the below screenshot:
 
Using MongoDB With ASP.NET Core Web API
 
Here, we create a new database called “EmployeeDB” and collection called “Employees” as shown below:
 
Using MongoDB With ASP.NET Core Web API
 
Once these two elements of the NoSQL database are created, we will add some documents to the collection as shown below:
 
Using MongoDB With ASP.NET Core Web API
 
Using MongoDB With ASP.NET Core Web API
 
Using MongoDB With ASP.NET Core Web API
 
We add data using the JSON format. Once the data is entered, we can also do some searching like using the SELECT statement in a SQL database. See below where we are finding all records with the given phone number.
 
Using MongoDB With ASP.NET Core Web API
 
Here you see that a unique object Id has been assigned to each document. We can use this object ID to update documents in the collection.
 

Accessing the MongoDB database from an ASP.NET Core Web API application

 
Finally, we will see how we can access the data from the MongoDB database. For this, we will create a ASP.NET Core 3.1 Web API application as shown below:
 
Using MongoDB With ASP.NET Core Web API
 
Using MongoDB With ASP.NET Core Web API
 
The first thing we will do is to add the MongoDB driver NuGet package. This will allow us to access the MongoDB database via friendly APIs.
 
Using MongoDB With ASP.NET Core Web API
 
Once this is done, we can proceed to start adding the code.
 
We first create a new folder called “Models” and add a new class “Employee.cs” to it as shown below:
  1. using MongoDB.Bson;  
  2. using MongoDB.Bson.Serialization.Attributes;  
  3.   
  4. namespace MongoDBWebAPI.Models  
  5. {  
  6.     public class Employee  
  7.     {  
  8.         [BsonId]  
  9.         [BsonRepresentation(BsonType.ObjectId)]  
  10.         public string Id { getset; }  
  11.   
  12.         public string Name { getset; }  
  13.   
  14.         public string Address { getset; }  
  15.   
  16.         public string Phone { getset; }  
  17.   
  18.         public string Email { getset; }  
  19.   
  20.     }  
  21. }  
We would also like to read the MongoDB settings from the appsettings.config file, using a strongly typed class and would hence create a new class file named “EmployeeDatabasesetting.cs” as below.
 
Appsettings.json
  1. {  
  2.   "EmployeeDatabaseSettings": {  
  3.     "EmployeesCollectionName""Employees",  
  4.     "ConnectionString""mongodb://localhost:27017",  
  5.     "DatabaseName""EmployeeDB"  
  6.   },  
  7.     "Logging": {  
  8.       "LogLevel": {  
  9.         "Default""Information",  
  10.         "Microsoft""Warning",  
  11.         "Microsoft.Hosting.Lifetime""Information"  
  12.       }  
  13.     },  
  14.     "AllowedHosts""*"  
  15. }  
EmployeeDatabasesetting.cs
  1. namespace MongoDBWebAPI.Models  
  2. {  
  3.     public class EmployeeDatabaseSettings : IEmployeeDatabaseSettings  
  4.     {  
  5.         public string EmployeesCollectionName { getset; }  
  6.         public string ConnectionString { getset; }  
  7.         public string DatabaseName { getset; }  
  8.     }  
  9.   
  10.     public interface IEmployeeDatabaseSettings  
  11.     {  
  12.         public string EmployeesCollectionName { getset; }  
  13.         public string ConnectionString { getset; }  
  14.         public string DatabaseName { getset; }  
  15.     }  
  16. }  
We do not want to call the Mongo API code directly from our controller class and hence we will create a service layer. For this, create a new folder called “Services” and add a new class called “EmployeeService.cs” to it as shown below:
  1. using MongoDB.Driver;  
  2. using MongoDBWebAPI.Models;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5.   
  6.   
  7. namespace MongoDBWebAPI.Services  
  8. {  
  9.     public class EmployeeService  
  10.     {  
  11.         private readonly IMongoCollection<Employee> _employees;  
  12.         public EmployeeService(IEmployeeDatabaseSettings settings)  
  13.         {  
  14.             var client = new MongoClient(settings.ConnectionString);  
  15.             var database = client.GetDatabase(settings.DatabaseName);  
  16.   
  17.             _employees = database.GetCollection<Employee>(settings.EmployeesCollectionName);  
  18.   
  19.         }  
  20.   
  21.         public List<Employee> Get()  
  22.         {  
  23.             List<Employee> employees;  
  24.             employees = _employees.Find(emp => true).ToList();  
  25.             return employees;  
  26.         }  
  27.   
  28.         public Employee Get(string id) =>  
  29.             _employees.Find<Employee>(emp => emp.Id == id).FirstOrDefault();  
  30.   
  31.     }  
  32. }  
Next, we add a new controller called “EmployeesController” as shown below:
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using MongoDBWebAPI.Models;  
  4. using MongoDBWebAPI.Services;  
  5.   
  6. namespace MongoDBWebAPI.Controllers  
  7. {  
  8.     [Route("api/[controller]")]  
  9.     [ApiController]  
  10.     public class EmployeesController : ControllerBase  
  11.     {  
  12.         private readonly EmployeeService _employeeService;  
  13.   
  14.         public EmployeesController(EmployeeService employeeService)  
  15.         {  
  16.             _employeeService = employeeService;  
  17.         }  
  18.   
  19.         [HttpGet]  
  20.         public ActionResult<List<Employee>> Get() =>  
  21.             _employeeService.Get();  
  22.   
  23.         [HttpGet("{id:length(24)}", Name = "GetEmployee")]  
  24.         public ActionResult<Employee> Get(string id)  
  25.         {  
  26.             var emp = _employeeService.Get(id);  
  27.   
  28.             if (emp == null)  
  29.             {  
  30.                 return NotFound();  
  31.             }  
  32.   
  33.             return emp;  
  34.         }  
  35.   
  36.     }  
  37. }  
The final step is to configure the required services in the Startup.cs file as shown below:
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Hosting;  
  6. using Microsoft.Extensions.Options;  
  7. using MongoDBWebAPI.Models;  
  8. using MongoDBWebAPI.Services;  
  9.   
  10. namespace MongoDBWebAPI  
  11. {  
  12.     public class Startup  
  13.     {  
  14.         public Startup(IConfiguration configuration)  
  15.         {  
  16.             Configuration = configuration;  
  17.         }  
  18.   
  19.         public IConfiguration Configuration { get; }  
  20.   
  21.         // This method gets called by the runtime. Use this method to add services to the container.  
  22.         public void ConfigureServices(IServiceCollection services)  
  23.         {  
  24.             services.Configure<EmployeeDatabaseSettings>(  
  25.                 Configuration.GetSection(nameof(EmployeeDatabaseSettings)));  
  26.   
  27.             services.AddSingleton<IEmployeeDatabaseSettings>(sp =>  
  28.                 sp.GetRequiredService<IOptions<EmployeeDatabaseSettings>>().Value);  
  29.   
  30.             services.AddSingleton<EmployeeService>();  
  31.   
  32.             services.AddControllers();  
  33.         }  
  34.   
  35.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  36.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  37.         {  
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.   
  43.             app.UseHttpsRedirection();  
  44.   
  45.             app.UseRouting();  
  46.   
  47.             app.UseAuthorization();  
  48.   
  49.             app.UseEndpoints(endpoints =>  
  50.             {  
  51.                 endpoints.MapControllers();  
  52.             });  
  53.         }  
  54.     }  
  55. }  
We can now run the application and browse to the Employees Controller as shown below:
 
Using MongoDB With ASP.NET Core Web API
 
Using MongoDB With ASP.NET Core Web API
 

Summary

 
In this article, we looked at NoSQL databases and MongoDB in particular. We saw how to install MongoDB and do some basic operations on it. This included creating a new database in the instance running on our machine, creating a collection inside the database, and then adding data called documents inside the collection. We then saw how to connect to MongoDB from an ASP.NET Core Web API application and how to read the data from the MongoDB database.