Getting Started With MongoDB In ASP.NET Core

Introduction

In this article, we will discuss the procedure to build a simple application in ASP.NET Core which communicates with MongoDB database.

Description

This application performs the CRUD operation on a Mongo database and then displays the details in a table.

Third-party Tools Used

Robo 3T – is a third-party tool which provides a lightweight MongoDB management tool.

Implementation - Setting up MongoDB

If you have not installed the MongoDB exe, then download and install the same from MongoDB Download Center

After installation of the database, in order to access the MongoDB, we have to start the MongoDB Process.

To start MongoDB, run mongod.exe in command prompt. Make sure that you are running the command prompt from installation folder of MongoDB.

By default, the installation path is set as C:\Program Files\MongoDB\Server\3.6\bin\

Additionally, we need a data directory to store all the data in MongoDB. User can set the path for data files using the –dbpath option to mongod.exe



You can begin using the Robo 3T after starting the MongoDB process.

For this demo, I have created a collection namely Customers with 3 columns.

Since the database is ready, now, we will start building the application. Follow along the article to create a sample application.

Below is a sample demonstration of the application we are going to make.


Create a new project in Visual Studio.



Select the template as ASP.NET Core MVC Web Application.



To interact with MongoDB from C# code, we need to install .NET MongoDB Driver which provides asynchronous interaction with MongoDB. I utilized the below NuGet commands to add the driver to my project. 
  1. Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.1  
  2. Install-Package MongoDB.Driver -Version 2.5.0  
Model Class

Let us make an entity class called “Customer” which fits the schema of the Customers table in the database.

  1. public class Customer  
  2.     {  
  3.         [BsonId]  
  4.         public ObjectId Id { getset; }  
  5.         [BsonElement]  
  6.         public int CustomerId { getset; }  
  7.         [BsonElement]  
  8.         public string CustomerName { getset; }  
  9.         [BsonElement]  
  10.         public string Address { getset; }  
  11.     }  

The class contains Id property of the type ObjectId. This property is used to match an item in MongoDB collections. We as well have another attribute, namely BsonElement which is applied to represent an “element” in the MongoDB collection.

Controller Methods

In Controller, we will add code for reading, editing, creating and deleting records from MongoDB. I have moved the code to retrieve the MongoDB database details to a common method.

  1. public class HomeController : Controller  
  2.     {  
  3.         private IMongoDatabase mongoDatabase;  
  4.   
  5.         //Generic method to get the mongodb database details  
  6.         public IMongoDatabase GetMongoDatabase()  
  7.         {  
  8.             var mongoClient = new MongoClient("mongodb://localhost:27017");  
  9.             return mongoClient.GetDatabase("CustomerDB");  
  10.         }  
  11.   
  12.         [HttpGet]  
  13.         public IActionResult Index()  
  14.         {  
  15.             //Get the database connection  
  16.             mongoDatabase = GetMongoDatabase();  
  17.             //fetch the details from CustomerDB and pass into view  
  18.             var result = mongoDatabase.GetCollection<Customer>("Customers").Find(FilterDefinition<Customer>.Empty).ToList();  
  19.             return View(result);  
  20.         }  
  21.   
  22.         [HttpGet]  
  23.         public IActionResult Create()  
  24.         {  
  25.             return View();  
  26.         }  
  27.   
  28.         [HttpPost]  
  29.         public IActionResult Create(Customer customer)  
  30.         {  
  31.             try  
  32.             {  
  33.                 //Get the database connection  
  34.                 mongoDatabase = GetMongoDatabase();  
  35.                 mongoDatabase.GetCollection<Customer>("Customers").InsertOne(customer);  
  36.             }  
  37.             catch (Exception ex)  
  38.             {  
  39.                 throw;  
  40.             }  
  41.             return RedirectToAction("Index");  
  42.         }  
  43.   
  44.         [HttpGet]  
  45.         public IActionResult Details(int? id)  
  46.         {  
  47.             if (id == null)  
  48.             {  
  49.                 return NotFound();  
  50.             }  
  51.             //Get the database connection  
  52.             mongoDatabase = GetMongoDatabase();  
  53.             //fetch the details from CustomerDB and pass into view  
  54.             Customer customer = mongoDatabase.GetCollection<Customer>("Customers").Find<Customer>(k => k.CustomerId == id).FirstOrDefault();  
  55.             if (customer == null)  
  56.             {  
  57.                 return NotFound();  
  58.             }  
  59.             return View(customer);  
  60.         }  
  61.   
  62.         [HttpGet]  
  63.         public IActionResult Delete(int? id)  
  64.         {  
  65.             if (id == null)  
  66.             {  
  67.                 return NotFound();  
  68.             }  
  69.             //Get the database connection  
  70.             mongoDatabase = GetMongoDatabase();  
  71.             //fetch the details from CustomerDB and pass into view  
  72.             Customer customer = mongoDatabase.GetCollection<Customer>("Customers").Find<Customer>(k => k.CustomerId == id).FirstOrDefault();  
  73.             if (customer == null)  
  74.             {  
  75.                 return NotFound();  
  76.             }  
  77.             return View(customer);  
  78.         }  
  79.   
  80.         [HttpPost]  
  81.         public IActionResult Delete(Customer customer)  
  82.         {  
  83.             try  
  84.             {  
  85.                 //Get the database connection  
  86.                 mongoDatabase = GetMongoDatabase();  
  87.                 //Delete the customer record  
  88.                 var result = mongoDatabase.GetCollection<Customer>("Customers").DeleteOne<Customer>(k => k.CustomerId == customer.CustomerId);  
  89.                 if (result.IsAcknowledged == false)  
  90.                 {  
  91.                     return BadRequest("Unable to Delete Customer " + customer.CustomerId);  
  92.                 }  
  93.             }  
  94.             catch (Exception ex)  
  95.             {  
  96.                 throw;  
  97.             }  
  98.             return RedirectToAction("Index");  
  99.         }  
  100.   
  101.         [HttpGet]  
  102.         public IActionResult Edit(int? id)  
  103.         {  
  104.             if (id == null)  
  105.             {  
  106.                 return NotFound();  
  107.             }  
  108.             //Get the database connection  
  109.             mongoDatabase = GetMongoDatabase();  
  110.             //fetch the details from CustomerDB based on id and pass into view  
  111.             var customer = mongoDatabase.GetCollection<Customer>("Customers").Find<Customer>(k => k.CustomerId == id).FirstOrDefault();  
  112.             if (customer == null)  
  113.             {  
  114.                 return NotFound();  
  115.             }  
  116.             return View(customer);  
  117.         }  
  118.   
  119.         [HttpPost]  
  120.         public IActionResult Edit(Customer customer)  
  121.         {  
  122.             try  
  123.             {  
  124.                 //Get the database connection  
  125.                 mongoDatabase = GetMongoDatabase();  
  126.                 //Build the where condition  
  127.                 var filter = Builders<Customer>.Filter.Eq("CustomerId", customer.CustomerId);  
  128.                 //Build the update statement   
  129.                 var updatestatement = Builders<Customer>.Update.Set("CustomerId", customer.CustomerId);  
  130.                 updatestatement = updatestatement.Set("CustomerName", customer.CustomerName);  
  131.                 updatestatement = updatestatement.Set("Address", customer.Address);  
  132.                 //fetch the details from CustomerDB based on id and pass into view  
  133.                 var result = mongoDatabase.GetCollection<Customer>("Customers").UpdateOne(filter, updatestatement);  
  134.                 if (result.IsAcknowledged == false)  
  135.                 {  
  136.                     return BadRequest("Unable to update Customer  " + customer.CustomerName);  
  137.                 }  
  138.             }  
  139.             catch (Exception ex)  
  140.             {  
  141.                 throw;  
  142.             }  
  143.   
  144.             return RedirectToAction("Index");  
  145.         }  
  146.   
  147.         public IActionResult About()  
  148.         {  
  149.             ViewData["Message"] = "Your application description page.";  
  150.   
  151.             return View();  
  152.         }  
  153.   
  154.         public IActionResult Contact()  
  155.         {  
  156.             ViewData["Message"] = "Your contact page.";  
  157.   
  158.             return View();  
  159.         }  
  160.   
  161.         public IActionResult Error()  
  162.         {  
  163.             return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });  
  164.         }  
  165.     }  
Code for MVC Views

Since this was a more of a MongoDB demo, I have used the scaffolding option available with MVC to generate View. You can modify this as per your needs.

InDeX vIEW

  1. @model IEnumerable<AspNetCoreMVCMongoDBDemo.Models.Customer>  
  2. @{  
  3.     ViewData["Title"] = "Index";  
  4. }  
  5. <h2>Index</h2>  
  6. <p>  
  7.     <a asp-action="Create">Create New</a>  
  8. </p>  
  9. <table class="table table-bordered" style="width:600px">  
  10.     <thead>  
  11.         <tr>  
  12.             <th>  
  13.                 @Html.DisplayNameFor(model => model.CustomerId)  
  14.             </th>  
  15.             <th>  
  16.                 @Html.DisplayNameFor(model => model.CustomerName)  
  17.             </th>  
  18.             <th>  
  19.                 @Html.DisplayNameFor(model => model.Address)  
  20.             </th>  
  21.             <th>Actions</th>  
  22.         </tr>  
  23.     </thead>  
  24.     <tbody>  
  25.         @foreach (var item in Model)  
  26.         {  
  27.             <tr>  
  28.                 <td>  
  29.                     @Html.DisplayFor(modelItem => item.CustomerId)  
  30.                 </td>  
  31.                 <td>  
  32.                     @Html.DisplayFor(modelItem => item.CustomerName)  
  33.                 </td>  
  34.                 <td>  
  35.                     @Html.DisplayFor(modelItem => item.Address)  
  36.                 </td>  
  37.                 <td>  
  38.                     @Html.ActionLink("Edit", "Edit", new { id = item.CustomerId }) |  
  39.                     @Html.ActionLink("Details", "Details", new { id = item.CustomerId }) |  
  40.                     @Html.ActionLink("Delete", "Delete", new { id = item.CustomerId })  
  41.                 </td>  
  42.             </tr>  
  43.         }  
  44.     </tbody>  
  45. </table>  

CREATE VIEW

  1. @model AspNetCoreMVCMongoDBDemo.Models.Customer  
  2. @{  
  3.     ViewData["Title"] = "Create";  
  4. }  
  5. <h2>Create Customer Details</h2>  
  6. <hr />  
  7. <div class="row">  
  8.     <div class="col-md-4">  
  9.         <form asp-action="Create">  
  10.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  11.             <div class="form-group">  
  12.                 <label asp-for="CustomerId" class="control-label"></label>  
  13.                 <input asp-for="CustomerId" class="form-control" />  
  14.                 <span asp-validation-for="CustomerId" class="text-danger"></span>  
  15.             </div>  
  16.             <div class="form-group">  
  17.                 <label asp-for="CustomerName" class="control-label"></label>  
  18.                 <input asp-for="CustomerName" class="form-control" />  
  19.                 <span asp-validation-for="CustomerName" class="text-danger"></span>  
  20.             </div>  
  21.             <div class="form-group">  
  22.                 <label asp-for="Address" class="control-label"></label>  
  23.                 <input asp-for="Address" class="form-control" />  
  24.                 <span asp-validation-for="Address" class="text-danger"></span>  
  25.             </div>  
  26.             <div class="form-group">  
  27.                 <input type="submit" value="Create" class="btn btn-default" />  
  28.             </div>  
  29.         </form>  
  30.     </div>  
  31. </div>  
  32. <div>  
  33.     <a asp-action="Index">Back to List</a>  
  34. </div>  
  35. @section Scripts {  
  36.     @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  37. }  

DELETE VIEW

  1. @model AspNetCoreMVCMongoDBDemo.Models.Customer  
  2. @{  
  3.     Layout = "_Layout";  
  4. }  
  5. <h4>Delete Customer</h4>  
  6. <div class="row">  
  7.     <div class="col-md-4">  
  8.         <form asp-action="Delete">  
  9.             <label class="control-label">Are you sure to delete </label> <input asp-for="CustomerId" class="form-control" readonly />  
  10.             <div class="form-group">  
  11.                 <input type="submit" value="Delete" class="btn btn-default" />  
  12.             </div>  
  13.         </form>  
  14.     </div>  
  15. </div>  
  16. <div>  
  17.     <a asp-action="Index">Back to List</a>  
  18. </div>  

DETAILS VIEW

  1. @model AspNetCoreMVCMongoDBDemo.Models.Customer  
  2. @{  
  3.     ViewData["Title"] = "Details";  
  4. }  
  5. <div>  
  6.     <h4>Customer Details</h4>  
  7.     <hr />  
  8.     <dl class="dl-horizontal">  
  9.         <dt>  
  10.             @Html.DisplayNameFor(model => model.CustomerId)  
  11.         </dt>  
  12.         <dd>  
  13.             @Html.DisplayFor(model => model.CustomerId)  
  14.         </dd>  
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.CustomerName)  
  17.         </dt>  
  18.         <dd>  
  19.             @Html.DisplayFor(model => model.CustomerName)  
  20.         </dd>  
  21.         <dt>  
  22.             @Html.DisplayNameFor(model => model.Address)  
  23.         </dt>  
  24.         <dd>  
  25.             @Html.DisplayFor(model => model.Address)  
  26.         </dd>  
  27.     </dl>  
  28. </div>  
  29. <div>  
  30.   
  31.     <a asp-action="Index">Back to List</a>  
  32. </div>  

EDIT VIEW

  1. @model AspNetCoreMVCMongoDBDemo.Models.Customer  
  2. @{  
  3.     Layout = "_Layout";  
  4. }  
  5. @{  
  6.     ViewData["Title"] = "Details";  
  7. }  
  8. <h2>Edit Customer Details</h2>  
  9. <hr />  
  10. <div class="row">  
  11.     <div class="col-md-4">  
  12.         <form asp-action="Edit">  
  13.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  14.             <div class="form-group">  
  15.                 <label asp-for="CustomerId" class="control-label"></label>  
  16.                 <input asp-for="CustomerId" class="form-control" />  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label asp-for="CustomerName" class="control-label"></label>  
  20.                 <input asp-for="CustomerName" class="form-control" />  
  21.                 <span asp-validation-for="CustomerName" class="text-danger"></span>  
  22.             </div>  
  23.             <div class="form-group">  
  24.                 <label asp-for="Address" class="control-label"></label>  
  25.                 <input asp-for="Address" class="form-control" />  
  26.                 <span asp-validation-for="Address" class="text-danger"></span>  
  27.             </div>  
  28.             <div class="form-group">  
  29.                 <input type="submit" value="Save" class="btn btn-default" />  
  30.             </div>  
  31.         </form>  
  32.     </div>  
  33. </div>  
  34. <div>  
  35.     <a asp-action="Index">Back to List</a>  
  36. </div>  
Conclusion

In this articlem we have looked into procedures to create a simple application in MVC Core using MongoDB as database.

You can download the source code for Asp.NetCoreMVCMongoDBDemo from GitHub.