Working With Mongo DB Using .Net Core

In this article, I'm going to show you how to deal with Mongo Database using .Net Core
 
There are many advantages and disadvantages of MongoDB. But one should keep in mind that MongoDB is very powerful when you deal with JSON data and it is lightweight, but the limitation is that It doesn't support Joins like SQL and each record (or) collection in MongoDB Cannot exceed more than 16MB.
 
Pre-Requisites
  1. Install MongoDb Server 2008 R2
  2. Install any MongoDB Management Studio (NoSQLBooster, Studio3T, Robo3T, etc.,)
  3. Consider as Localhost (IPaddress to continue with remote server) with default port 27017
  4. Create a new Database and Collection ( nothing but like a table in SQL )
Sample Image (In NoSQLBooster)
 
 
 
Now follow the below steps for the coding. 
 
Step 1
 
Create a new Asp.Net Core Project in Visual Studio and Declare the Mongo Connection Properties For the Controller (Here I declared for Home Controller)
 
Code For Declaration
  1. pubilc HomeController() {  
  2.  var mongoClient = new MongoClient("mongodb://localhost:27017");  
  3.  IMongoDatabase db = mongoClient.GetDatabase("practice");  
  4.  this.collection = db.GetCollection < Customer > ("santhosh");  
  5.  return mongoClient.GetDatabase("practice");  
  6. }  
Here I declared a global variable named collection, we can use this collection in the entire controller.
 
Queries
 
Insert
 
collection.InsertOne(customer);     // Here customer is my model object
collection.InsertMany(customer);     // InsertMany function is used to insert multiple records
 
Update
 
collection.UpdateOne(filter, updatestatement);      // filter is used to define that which collection you need to update
collection.UpdateMany(filter, updatestatement);
 
Get
 
collection.Find(FilterDefinition.Empty).ToList();       // to get all the records in the particular collection
collection.Find(k => k.No == id).FirstOrDefault();     // to get the particular record
 
Delete
 
collection.DeleteOne(k => k.No == customer.No);      // to delete the particular record
 
Step 2
 
Install MongoDB.Driver from Nuget Package Manager
 
Step 3
 
Declare the Properties in the Model Class appropriate to your data which you want to save
 
Code for Model Class
  1. public class Customer {  
  2.  [BsonId]  
  3.  public ObjectId _id {  
  4.   get;  
  5.   set;  
  6.  }  
  7.  [BsonElement]  
  8.  public string No {  
  9.   get;  
  10.   set;  
  11.  }  
  12.  [BsonElement]  
  13.  public string Name {  
  14.   get;  
  15.   set;  
  16.  }  
  17.  [BsonElement]  
  18.  public string Course {  
  19.   get;  
  20.   set;  
  21.  }  
  22.  [BsonElement]  
  23.  public string Address {  
  24.   get;  
  25.   set;  
  26.  }  
  27. }  
BsonId is the auto-generated ID for each and every record in MongoDB and it is mandatory for unique identification.
 
BsonElement is not mandatory.
 
Step 4
 
Create an Action Method with Name "Index" in Home Controller
 
Code for Index Method
  1. [HttpGet]  
  2. public IActionResult Index() {  
  3.  var result = collection.Find(FilterDefinition < Customer > .Empty).ToList();  
  4.  return View(result);  
  5. }  
Source code for 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.No)    
  14. </th>    
  15. <th>    
  16. @Html.DisplayNameFor(model => model.Name)    
  17. </th>    
  18. <th>    
  19. @Html.DisplayNameFor(model => model.Course)    
  20. </th>    
  21. <th>    
  22. @Html.DisplayNameFor(model => model.Address)    
  23. </th>    
  24. <th>Actions</th>    
  25. </tr>    
  26. </thead>    
  27. <tbody>    
  28. @foreach (var item in Model)    
  29. {    
  30. <tr>    
  31. <td>    
  32. @Html.DisplayFor(modelItem => item.No)    
  33. </td>    
  34. <td>    
  35. @Html.DisplayFor(modelItem => item.Name)    
  36. </td>    
  37. <td>    
  38. @Html.DisplayFor(modelItem => item.Course)    
  39. </td>    
  40. <td>    
  41. @Html.DisplayFor(modelItem => item.Address)    
  42. </td>    
  43. <td>    
  44. @Html.ActionLink("Edit""Edit"new { id = item.No }) |    
  45. @Html.ActionLink("Details""Details"new { id = item.No }) |    
  46. @Html.ActionLink("Delete""Delete"new { id = item.No })    
  47. </td>    
  48. </tr>    
  49. }    
  50. </tbody>    
  51. </table>    
Step 5
 
Add the Create method in the home controller with both get and post attributes.
  1. [HttpGet]  
  2. public IActionResult Create() {  
  3.  return View();  
  4. }  
  5.   
  6. [HttpPost]  
  7. public IActionResult Create(Customer customer) {  
  8.  try {  
  9.   collection.InsertOne(customer);  
  10.  } catch (Exception ex) {  
  11.   throw;  
  12.  }  
  13.  return RedirectToAction("Index");  
  14. } 
Code for 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="No" class="control-label"></label>    
  13. <input asp-for="No" class="form-control" />    
  14. <span asp-validation-for="No" class="text-danger"></span>    
  15. </div>    
  16. <div class="form-group">    
  17. <label asp-for="Name" class="control-label"></label>    
  18. <input asp-for="Name" class="form-control" />    
  19. <span asp-validation-for="Name" class="text-danger"></span>    
  20. </div>    
  21. <div class="form-group">    
  22. <label asp-for="Course" class="control-label"></label>    
  23. <input asp-for="Course" class="form-control" />    
  24. <span asp-validation-for="Course" class="text-danger"></span>    
  25. </div>    
  26. <div class="form-group">    
  27. <label asp-for="Address" class="control-label"></label>    
  28. <input asp-for="Address" class="form-control" />    
  29. <span asp-validation-for="Address" class="text-danger"></span>    
  30. </div>    
  31. <div class="form-group">    
  32. <input type="submit" value="Create" class="btn btn-default" />    
  33. </div>    
  34. </form>    
  35. </div>    
  36. </div>    
  37. <div>    
  38. <a asp-action="Index">Back to List</a>    
  39. </div>    
  40. @section Scripts {    
  41. @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}    
  42. } 
Step 6
 
Add the details method to the home controller.
 
Code for Details Method
  1. [HttpGet]  
  2. public IActionResult Details(string id) {  
  3.  if (id == null) {  
  4.   return NotFound();  
  5.  }  
  6.  //Get the database connection    
  7.  //mongoDatabase = GetMongoDatabase();    
  8.  //fetch the details from CustomerDB and pass into view    
  9.  Customer customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();  
  10.  if (customer == null) {  
  11.   return NotFound();  
  12.  }  
  13.  return View(customer);  
  14. } 
Code for 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.No)    
  11. </dt>    
  12. <dd>    
  13. @Html.DisplayFor(model => model.No)    
  14. </dd>    
  15. <dt>    
  16. @Html.DisplayNameFor(model => model.Name)    
  17. </dt>    
  18. <dd>    
  19. @Html.DisplayFor(model => model.Name)    
  20. </dd>    
  21. <dt>    
  22. @Html.DisplayNameFor(model => model.Course)    
  23. </dt>    
  24. <dd>    
  25. @Html.DisplayFor(model => model.Course)    
  26. </dd>    
  27. <dt>    
  28. @Html.DisplayNameFor(model => model.Address)    
  29. </dt>    
  30. <dd>    
  31. @Html.DisplayFor(model => model.Address)    
  32. </dd>    
  33. </dl>    
  34. </div>    
  35. <div>    
  36. <a asp-action="Index">Back to List</a>    
  37. </div>  
Step 7
 
Add Edit Method
 
Code for Edit Method
  1. [HttpGet]  
  2. public IActionResult Edit(string id) {  
  3.   if (id == null) {  
  4.    return NotFound();  
  5.   }  
  6.   //Get the database connection    
  7.   //mongoDatabase = GetMongoDatabase();    
  8.   //fetch the details from CustomerDB based on id and pass into view    
  9.   var customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();  
  10.   if (customer == null) {  
  11.    return NotFound();  
  12.   }  
  13.   return View(customer);  
  14.  }  
  15.  [HttpPost]  
  16. public IActionResult Edit(Customer customer) {  
  17.  try {  
  18.   var filter = Builders < Customer > .Filter.Eq("No", customer.No);  
  19.   var updatestatement = Builders < Customer > .Update.Set("No", customer.No);  
  20.   updatestatement = updatestatement.Set("Name", customer.Name);  
  21.   updatestatement = updatestatement.Set("Course", customer.Course);  
  22.   updatestatement = updatestatement.Set("Address", customer.Address);  
  23.   var result = collection.UpdateOne(filter, updatestatement);  
  24.   if (result.IsAcknowledged == false) {  
  25.    return BadRequest("Unable to update Customer " + customer.Name);  
  26.   }  
  27.  } catch (Exception ex) {  
  28.   throw;  
  29.  }  
  30.  return RedirectToAction("Index");  
  31. } 
Source code for 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="No" class="control-label"></label>    
  16. <input asp-for="No" class="form-control" />    
  17. </div>    
  18. <div class="form-group">    
  19. <label asp-for="Name" class="control-label"></label>    
  20. <input asp-for="Name" class="form-control" />    
  21. <span asp-validation-for="Name" class="text-danger"></span>    
  22. </div>    
  23. <div class="form-group">    
  24. <label asp-for="Course" class="control-label"></label>    
  25. <input asp-for="Course" class="form-control" />    
  26. <span asp-validation-for="Course" class="text-danger"></span>    
  27. </div>    
  28. <div class="form-group">    
  29. <label asp-for="Address" class="control-label"></label>    
  30. <input asp-for="Address" class="form-control" />    
  31. <span asp-validation-for="Address" class="text-danger"></span>    
  32. </div>    
  33. <div class="form-group">    
  34. <input type="submit" value="Save" class="btn btn-default" />    
  35. </div>    
  36. </form>    
  37. </div>    
  38. </div>    
  39. <div>    
  40. <a asp-action="Index">Back to List</a>    
  41. </div> 
Step 8
 
Add Delete Method
 
Source code for Delete Method
  1. [HttpGet]  
  2. public IActionResult Delete(string id) {  
  3.   if (id == null) {  
  4.    return NotFound();  
  5.   }  
  6.   Customer customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();  
  7.   if (customer == null) {  
  8.    return NotFound();  
  9.   }  
  10.   return View(customer);  
  11.  }  
  12.  [HttpPost]  
  13. public IActionResult Delete(Customer customer) {  
  14.  try {  
  15.   var result = collection.DeleteOne < Customer > (k => k.No == customer.No);  
  16.   if (result.IsAcknowledged == false) {  
  17.    return BadRequest("Unable to Delete Customer " + customer.No);  
  18.   }  
  19.  } catch (Exception ex) {  
  20.   throw;  
  21.  }  
  22.  return RedirectToAction("Index");  
  23. } 
Source code for 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="No" 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> 
Step 9
 
Add About Us and Contact Us method
 
Code for About Us and Contact Us Methods
  1. public IActionResult About() {  
  2.  ViewData["Message"] = "Your application description page.";  
  3.  return View();  
  4. }  
  5. public IActionResult Contact() {  
  6.  ViewData["Message"] = "Your contact page.";  
  7.  return View();  
  8. } 
Code for About Us and Contact Us Views
 
About Us
  1. @{    
  2. ViewData["Title"] = "About";    
  3. }    
  4. <h2>@ViewData["Title"]</h2>    
  5. <h3>@ViewData["Message"]</h3>    
  6. <p>Use this area to provide additional information.</p>  
Contact Us
  1. @{    
  2. ViewData["Title"] = "Contact";    
  3. }    
  4. <h2>@ViewData["Title"]</h2>    
  5. <h3>@ViewData["Message"]</h3>    
  6. <address>    
  7. One Microsoft Way<br />    
  8. Redmond, WA 98052-6399<br />    
  9. <abbr title="Phone">P:</abbr>    
  10. 425.555.0100    
  11. </address>    
  12. <address>    
  13. <strong>Support:</strong> <a href="mailto:[email protected]">Santhosh Teja</a><br />    
  14. <strong>Marketing:</strong> <a href="mailto:[email protected]">Ponnapalli Santhosh Teja</a>    
  15. </address>   
Now I added Index, Details, Create, Update and Delete methods.
 
Using these methods you can insert, get, update and delete the records in a collection in MongoDB 
 
Analysis
 
Now I added Index, Details, Create, Update and Delete methods.
 
Using these methods you can insert, get, update and delete the records in a collection in MongoDB.
 
Sample Image For Index
 
When you build and run the project you can see the output of the Index method as seen in the below image. 
 
 
 
Sample Image For Create
 
You can enter the data by clicking the Create Button and save the data by clicking the Save button.
 
 
 
Sample Image For Index
 
 
 
Sample Image For Edit
 
 
 
Sample Image For Details
 
 
 
Sample Image For Delete
 
 
 
Thanks for reading this article.
 
All the best in your endeavors!