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.
- Install MongoDb Server 2008 R2
- Install any MongoDB Management Studio (NoSQLBooster, Studio3T, Robo3T, etc.,)
- Consider as Localhost (IPaddress to continue with remote server) with default port 27017
- 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
- pubilc HomeController() {
- var mongoClient = new MongoClient("mongodb://localhost:27017");
- IMongoDatabase db = mongoClient.GetDatabase("practice");
- this.collection = db.GetCollection < Customer > ("santhosh");
- return mongoClient.GetDatabase("practice");
- }
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
- public class Customer {
- [BsonId]
- public ObjectId _id {
- get;
- set;
- }
- [BsonElement]
- public string No {
- get;
- set;
- }
- [BsonElement]
- public string Name {
- get;
- set;
- }
- [BsonElement]
- public string Course {
- get;
- set;
- }
- [BsonElement]
- public string Address {
- get;
- set;
- }
- }
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
- [HttpGet]
- public IActionResult Index() {
- var result = collection.Find(FilterDefinition < Customer > .Empty).ToList();
- return View(result);
- }
Source code for Index View
- @model IEnumerable<AspNetCoreMVCMongoDBDemo.Models.Customer>
- @{
- ViewData["Title"] = "Index";
- }
- <h2>Index</h2>
- <p>
- <a asp-action="Create">Create New</a>
- </p>
- <table class="table table-bordered" style="width:600px">
- <thead>
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.No)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Course)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Address)
- </th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var item in Model)
- {
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.No)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Course)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Address)
- </td>
- <td>
- @Html.ActionLink("Edit", "Edit", new { id = item.No }) |
- @Html.ActionLink("Details", "Details", new { id = item.No }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.No })
- </td>
- </tr>
- }
- </tbody>
- </table>
Step 5
Add the Create method in the home controller with both get and post attributes.
- [HttpGet]
- public IActionResult Create() {
- return View();
- }
-
- [HttpPost]
- public IActionResult Create(Customer customer) {
- try {
- collection.InsertOne(customer);
- } catch (Exception ex) {
- throw;
- }
- return RedirectToAction("Index");
- }
Code for Create View
- @model AspNetCoreMVCMongoDBDemo.Models.Customer
- @{
- ViewData["Title"] = "Create";
- }
- <h2>Create Customer Details</h2>
- <hr />
- <div class="row">
- <div class="col-md-4">
- <form asp-action="Create">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="No" class="control-label"></label>
- <input asp-for="No" class="form-control" />
- <span asp-validation-for="No" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Name" class="control-label"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Course" class="control-label"></label>
- <input asp-for="Course" class="form-control" />
- <span asp-validation-for="Course" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Address" class="control-label"></label>
- <input asp-for="Address" class="form-control" />
- <span asp-validation-for="Address" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
- @section Scripts {
- @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
- }
Step 6
Add the details method to the home controller.
Code for Details Method
- [HttpGet]
- public IActionResult Details(string id) {
- if (id == null) {
- return NotFound();
- }
-
-
-
- Customer customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();
- if (customer == null) {
- return NotFound();
- }
- return View(customer);
- }
Code for Details View
- @model AspNetCoreMVCMongoDBDemo.Models.Customer
- @{
- ViewData["Title"] = "Details";
- }
- <div>
- <h4>Customer Details</h4>
- <hr />
- <dl class="dl-horizontal">
- <dt>
- @Html.DisplayNameFor(model => model.No)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.No)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Name)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Name)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Course)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Course)
- </dd>
- <dt>
- @Html.DisplayNameFor(model => model.Address)
- </dt>
- <dd>
- @Html.DisplayFor(model => model.Address)
- </dd>
- </dl>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
Step 7
Add Edit Method
Code for Edit Method
- [HttpGet]
- public IActionResult Edit(string id) {
- if (id == null) {
- return NotFound();
- }
-
-
-
- var customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();
- if (customer == null) {
- return NotFound();
- }
- return View(customer);
- }
- [HttpPost]
- public IActionResult Edit(Customer customer) {
- try {
- var filter = Builders < Customer > .Filter.Eq("No", customer.No);
- var updatestatement = Builders < Customer > .Update.Set("No", customer.No);
- updatestatement = updatestatement.Set("Name", customer.Name);
- updatestatement = updatestatement.Set("Course", customer.Course);
- updatestatement = updatestatement.Set("Address", customer.Address);
- var result = collection.UpdateOne(filter, updatestatement);
- if (result.IsAcknowledged == false) {
- return BadRequest("Unable to update Customer " + customer.Name);
- }
- } catch (Exception ex) {
- throw;
- }
- return RedirectToAction("Index");
- }
Source code for Edit View
- @model AspNetCoreMVCMongoDBDemo.Models.Customer
- @{
- Layout = "_Layout";
- }
- @{
- ViewData["Title"] = "Details";
- }
- <h2>Edit Customer Details</h2>
- <hr />
- <div class="row">
- <div class="col-md-4">
- <form asp-action="Edit">
- <div asp-validation-summary="ModelOnly" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="No" class="control-label"></label>
- <input asp-for="No" class="form-control" />
- </div>
- <div class="form-group">
- <label asp-for="Name" class="control-label"></label>
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Course" class="control-label"></label>
- <input asp-for="Course" class="form-control" />
- <span asp-validation-for="Course" class="text-danger"></span>
- </div>
- <div class="form-group">
- <label asp-for="Address" class="control-label"></label>
- <input asp-for="Address" class="form-control" />
- <span asp-validation-for="Address" class="text-danger"></span>
- </div>
- <div class="form-group">
- <input type="submit" value="Save" class="btn btn-default" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
Step 8
Add Delete Method
Source code for Delete Method
- [HttpGet]
- public IActionResult Delete(string id) {
- if (id == null) {
- return NotFound();
- }
- Customer customer = collection.Find < Customer > (k => k.No == id).FirstOrDefault();
- if (customer == null) {
- return NotFound();
- }
- return View(customer);
- }
- [HttpPost]
- public IActionResult Delete(Customer customer) {
- try {
- var result = collection.DeleteOne < Customer > (k => k.No == customer.No);
- if (result.IsAcknowledged == false) {
- return BadRequest("Unable to Delete Customer " + customer.No);
- }
- } catch (Exception ex) {
- throw;
- }
- return RedirectToAction("Index");
- }
Source code for Delete View
- @model AspNetCoreMVCMongoDBDemo.Models.Customer
- @{
- Layout = "_Layout";
- }
- <h4>Delete Customer</h4>
- <div class="row">
- <div class="col-md-4">
- <form asp-action="Delete">
- <label class="control-label">Are you sure to delete </label> <input asp-for="No" class="form-control" readonly />
- <div class="form-group">
- <input type="submit" value="Delete" class="btn btn-default" />
- </div>
- </form>
- </div>
- </div>
- <div>
- <a asp-action="Index">Back to List</a>
- </div>
Step 9
Add About Us and Contact Us method
Code for About Us and Contact Us Methods
- public IActionResult About() {
- ViewData["Message"] = "Your application description page.";
- return View();
- }
- public IActionResult Contact() {
- ViewData["Message"] = "Your contact page.";
- return View();
- }
Code for About Us and Contact Us Views
About Us
- @{
- ViewData["Title"] = "About";
- }
- <h2>@ViewData["Title"]</h2>
- <h3>@ViewData["Message"]</h3>
- <p>Use this area to provide additional information.</p>
Contact Us
- @{
- ViewData["Title"] = "Contact";
- }
- <h2>@ViewData["Title"]</h2>
- <h3>@ViewData["Message"]</h3>
- <address>
- One Microsoft Way<br />
- Redmond, WA 98052-6399<br />
- <abbr title="Phone">P:</abbr>
- 425.555.0100
- </address>
- <address>
- <strong>Support:</strong> <a href="mailto:[email protected]">Santhosh Teja</a><br />
- <strong>Marketing:</strong> <a href="mailto:[email protected]">Ponnapalli Santhosh Teja</a>
- </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!