Category Archives: MongoDB

Create a Restful API with ASP.NET Core and MongoDB

In this article, I will create a web API with ASP.NET Core that performs CRUD (Create, Read, Update, and Delete) operations on a MongoDB NoSQL database.

First, I will start with configuring MongoDB to perform CRUD operations from a web API.

By default, MongoDB is installed at C:\Program Files\MongoDB\Server\4.0\bin.

To access MongoDB Shell, you must add C:\Program Files\MongoDB\Server\4.0\bin to the Path environment variable.

To create a database, use MongoDB Compass Community or MongoDB Shell

For more information about MongoDB Shell commands, you can look at https://docs.mongodb.com/manual/mongo/#working-with-the-mongo-shell

For MongoDB Shell, choose a directory such as C:\Users\casan\Desktop\Files\mongodb.

I created a new folder named mongodb at C:\Users\casan\Desktop\Files on my development machine.

Open a command line, run the following command to connect to MongoDB on default port 27017.

mongod --dbpath <data_directory_path>

Open another command prompt and run the following command to connect to the default test database.

mongo

Run the following command. If testDb database doesn’t exist, it is created.

use testDb

Create a Employees collection by running the following command

db.createCollection('Employees')

Run the following command to insert three documents.

db.Employees.insertMany([{'Name':'Cihan','Salary':10000.00,'Company':'ABC'}, {'Name':'Mike','Salary':7000.00,'Company':'XYZ'}, {'Name':'John','Salary':7500.00,'Company':'DEF'}])

View the documents.

db.Employees.find({}).pretty()

That’s it for the database side

Now, let’s create the ASP.NET Core web API project.

Open Visual Studio 2017 Community

Go to File > New > Project

Select the ASP.NET Core Web Application option.

Select the .NET Core framework and ASP.NET Core 2.1.

Select the API project template. Then click OK.


In Solution Explorer, Right click the Dependencies section and select the Manage NuGet Packages.. option to install .NET Driver for MongoDB.

Install MongoDB.Driver

To add a model, create a folder named Models to the project root as you see below.

Then add a class named Employee.cs with the following code to the Models folder.

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

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

        [BsonElement("Name")]
        public string Name { get; set; }

        [BsonElement("Salary")]
        public decimal Salary { get; set; }

        [BsonElement("Company")]
        public string Company { get; set; }

    }
}

[BsonElement] attribute is used to represent the property name in the MongoDB collection

[BsonId] is used to assign the Id property as the primary key.

[BsonRepresentation(BsonType.ObjectId)] is used to pass the parameter as the string type instead of ObjectId.
Mongo handles the conversion.

These are all required to map the Common Language Runtime object to the MongoDB collection.


For CRUD operations, create a folder named Services to the project root and add a class named EmployeeService.cs with the following code to the Services folder that is created.

using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;

namespace WebApplication1.Services
{
    public class EmployeeService
    {
        private readonly IMongoCollection _employees;

        public EmployeeService(IConfiguration config)
        {
            var client = new MongoClient(config.GetConnectionString("testDb"));
            var database = client.GetDatabase("testDb");
            _employees = database.GetCollection("Employees");
        }

        public List Get()
        {
            return _employees.Find(employee => true).ToList();
        }

        public Employee Get(string id)
        {
            return _employees.Find(employee => employee.Id == id).FirstOrDefault();
        }

        public Employee Create(Employee employee)
        {
            _employees.InsertOne(employee);
            return employee;
        }

        public void Update(string id, Employee employeeParam)
        {
            _employees.ReplaceOne(employee => employee.Id == id, employeeParam);
        }

        public void Delete(Employee employeeParam)
        {
            _employees.DeleteOne(employee => employee.Id == employeeParam.Id);
        }

        public void Delete(string id)
        {
            _employees.DeleteOne(employee => employee.Id == id);
        }
    }
}

Add the MongoDB connection string to the appsettings.json file.

{
  "ConnectionStrings": {
    "testDb": "mongodb://localhost:27017"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Register the EmployeeService class with the Dependency Injection system to the ConfigureServices method in the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

IMongoDatabase represents the Mongo database. The generic GetCollection(collection) method is used to gain access to data for a specific collection.

GetCollection(Employee) returns a MongoCollection object to represent the collection

Add a controller class named EmployeesController with the following code to the Controller folder.

using System.Collections.Generic;
using WebApplication1.Models;
using WebApplication1.Services;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeesController : Controller
    {
        private readonly EmployeeService _employeeService;

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

        [HttpGet]
        public ActionResult> Get()
        {
            return _employeeService.Get();
        }

        [HttpGet("{id:length(24)}", Name = "GetEmployee")]
        public ActionResult Get(string id)
        {
            var employee = _employeeService.Get(id);

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

            return employee;
        }

        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            _employeeService.Create(employee);

            return CreatedAtRoute("GetEmployee", new { id = employee.Id.ToString() }, employee);
        }

        [HttpPut("{id:length(24)}")]
        public IActionResult Update(string id, Employee employeeParam)
        {
            var employee = _employeeService.Get(id);

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

            _employeeService.Update(id, employeeParam);

            return NoContent();
        }

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

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

            _employeeService.Delete(employee.Id);

            return NoContent();
        }
    }
}

Build and start the app.

Navigate to http://localhost:/api/employees in your browser.

This tutorial also uses Postman to test the web API.

Open Postman and set the Http method to POST.

Set the request URL to http://localhost:<port>/api/employees.

Select the Body tab.

Select the raw radio button.

Set the type to JSON (application/json).

In the request body, enter the following JSON data to register an employee.

{"Name":"Robert","Salary":8000.00,"Company":"UPS"}

Select Send.

In the response headers, copy the value of the location

Select the Headers tab in the Response pane.

Copy the Location header value.

Paste the URI to your browser.