Use this link for downloading the project.
In this article, we are going to learn how to perform simple CRUD operations using ASP.NET MVC and MongoDB. If you are new to MongoDB and want to know the basics, then just click on the below link to kick start your tour with Mongo.
Most people nowadays want to use open source products available in the market. Here is yet another product called MongoDB which is a No SQL database that stores data in JSON object format and also calls a BSON document.
Many people might think that it is open source database and we cannot use this kind of database with .NET applications. But, I say that we can use this database with.NET too. That is good news, right ?
MongoDB provides a driver called mongocsharp driver which we need to download and install from NuGet Package Manager into application to connect to MongoDB database. It is simple to use, and finally we are going to perform simple CRUD operation which will give a basic idea of how to use this database, how data is stored, and how we can pull data from the database as per our needs.
Before starting, let’s have a look at the topics.
Topic
- Create MVC Application
- Adding mongocsharp driver form NuGet Package
- Connecting to MongoDB database.
- Setting connecting string.
- Adding Model
- Adding Controller CarinformationController
- Performing CRUD operation
- CREATE
- READ (Single / Multiple) Document
- EDIT / UPDATE
- DELETE
Let’s begin our journey to learn simple CRUD operation with ASP.NET MVC using MongoDB.
Create MVC application
Open Visual Studio IDE and click on "New Project" link. A "New Project" dialog will pop up.
Inside that, from left pane choose templates ➜ choose Visual C# ➜ Web template. Then, in the middle pane, you will see the list of ASP.NET Web Application templates. Select ASP.NET Web Application (.NET Framework)" project templates.
Enter the project name “MongoDemo” and finally click on the OK button.
After that, a new dialog will pop up with name “New ASP.NET Web Application”. In this, we are going to choose MVC project template and click on OK button for creating a project.
Below is complete project view which is newly created
After creating a new project, in the next step, we are going to add a mongocsharp driver to the project.
Adding mongocsharp driver form NuGet Package
To add mongocsharp driver, just right click on the project and from the list of menu, choose "Manage NuGet Package".
A new dialog will pop up where we are going to choose Browse tab. In search box, type “mongocsharp driver” which will show a list of other NuGet packages. Select the first one and click on "Install" button to install it in the project.
After installing, you can see project reference where you will find MongoDB driver reference too.
Now, we have installed “mongocsharp driver” successfully. Now, we are going to connect to MongoDB database.
Connecting to MongoDB database
In this step, we are going to connect MVC application with MongoDB database.
Starting MongoDB Server
In this part, we are going to start MongoDB Server.
Starting MongoDB Client
In this part, we are going to start MongoDB Client.
After starting the Server and client, next we are going to create database.
Creating a New Database in MongoDB
In this part, we are going to creating the database first with name “CarDatabase”.
After we have created database next step we are going to set credentials for this database such that application having valid credentials can only access this database.
Database credentials
Username: - demouser
Password: -Pass@123
Below is snapshot of how to set credentials to database
After adding the database and setting the credentials for the database next we are going create a context class for central accessing MongoDB database settings.
Setting Connecting string
In this part we are going create a class with name MongoContext in App_Start folder.
After creating class next we are going to set all credentials in Web.config appSettings sections.
It is easy to update any setting in the future if some details have changed. Now we need to deploy the code -- just a change in the Web.config file and it is done.
Below is snapshot of appSettings
Code Snippet
- <appSettings>
- <add key="MongoDatabaseName" value="CarDatabase" />
- <add key="MongoUsername" value="demouser" />
- <add key="MongoPassword" value="Pass@123" />
- <add key="MongoPort" value="27017" />
- <add key="MongoHost" value="localhost" />
- </appSettings>
After finishing with appSettings next we are going read this value in MongoContext class.
MongoContext Class Code snippet
In this class first we have declared 3 variables
- MongoClient
- MongoServer
- MongoDatabase
Then in the constructor of the class, we are getting values of Mongo Database from appSettings which we have set. Next we are passing these values to [MongoCredential.CreateMongoCRCredential] method for creating MongoCredential, and then in the next step, we are setting MongoClientSettings, for this setting we need to pass MongoCredential; along with that, we need to pass Host name and Port number of MongoDB.
Code Snippet
- using MongoDB.Driver;
- using System;
- using System.Configuration;
-
- namespace MongoDemo.App_Start
- {
- public class MongoContext
- {
- MongoClient _client;
- MongoServer _server;
- public MongoDatabase _database;
- public MongoContext()
- {
-
- var MongoDatabaseName = ConfigurationManager.AppSettings["MongoDatabaseName"];
- var MongoUsername = ConfigurationManager.AppSettings["MongoUsername"];
- var MongoPassword = ConfigurationManager.AppSettings["MongoPassword"];
- var MongoPort = ConfigurationManager.AppSettings["MongoPort"];
- var MongoHost = ConfigurationManager.AppSettings["MongoHost"];
-
-
- var credential = MongoCredential.CreateMongoCRCredential
- (MongoDatabaseName,
- MongoUsername,
- MongoPassword);
-
-
- var settings = new MongoClientSettings
- {
- Credentials = new[] { credential },
- Server = new MongoServerAddress(MongoHost, Convert.ToInt32(MongoPort))
- };
- _client = new MongoClient(settings);
- _server = _client.GetServer();
- _database = _server.GetDatabase(MongoDatabaseName);
- }
- }
- }
After we have completed with setting up connecting string in the next step we are going to adding Model which is going to be table.
Adding Model
In this part we are going to add a model (a class) in Models folder with name “CarModel”, and properties inside CarModel are decorated with MongoDB attribute.
Note
Attributes used to control Bson serialization/deserialization.
After adding model next we are going add a controller with name CarinformationController.
Adding Controller
For adding controller just right click on controller folder and choose add menu and inside that choose controller menu a new dialog pop up with name “Add scaffold” in this just choose “MVC 5 Controller with read/write actions” and click on add button.
After clicking on Add button a new dialog will pop up with name “Add Controller” and it is going to ask for Controller name and we are going to name Controller as CarinformationController and finally, click on Add button to add a controller.
After clicking on add button it is going to create CarinformationController and along with it is also going to add default action method [Create, Index, Edit, Delete, and Details] as shown in below snapshot.
After adding controller the first thing we are going to work on is to add a constructor to Controller for initializing MongoDB objects.
Code snippet
- MongoContext _dbContext;
- public CarinformationController()
- {
- _dbContext = new MongoContext();
- }
After initializing MongoDB objects next we are going to start performing CRUD operation.
CREATE
After adding Constructor next we are going to edit Create Action Method for adding “Create” View to take input.
For adding view just right click inside Create Action Method and choose Add View from the list of the menu. After choosing that a new dialog will pop up with name Add View in this dialog just choose template “Create” and Model class as “CarModel” click on Add button.
After adding view below is snapshot of code view and browser view of “Create” View
Now let’s write code to insert data in the database.
In this part we are going to insert data into database, and for doing that first we need to create MongoCollection object.
Code Snippet
- var document = _dbContext._database.GetCollection<BsonDocument>("CarModel");
In the next step, we have added a filter to check duplication of the document.
- var query = Query.And(Query.EQ("Carname", carmodel.Carname), Query.EQ("Color", carmodel.Color));
-
- var count = document.FindAs<CarModel>(query).Count();
-
- if (count == 0)
- {
- var result = document.Insert(carmodel);
- }
- else
- {
- TempData["Message"] = "Carname ALready Exist";
- return View("Create", carmodel);
- }
Passing Model to insert data after check
- var result = document.Insert(carmodel);
Snapshot of Create ActionMethod
Now let’s save the code and run the application.
After running the application just access URL - http://localhost:####/Carinformation/Create
After accessing it a create view will appear as shown in the below snapshot.
Fill details of form and click on submit button to save data in MongoDB database (“CarDatabase”).
After clicking on insert button data is inserted into (“CarDatabase”) and we get response ok as 1.
Wow, we have to insert the first document into MongoDB database. Next we are going to Read data from inserted data.
READ [Multiple Document]
In this part, we are going to display records in a Grid format which we have saved in MongoDB database.
For displaying all records we are going to use FindAll() method of MongoDB as shown in below snapshot.
Snapshot of Index ActionMethod
Code Snippet
- public ActionResult Index()
- {
- var carDetails = _dbContext._database.GetCollection<CarModel>("CarModel").FindAll().ToList();
- return View(carDetails);
- }
Now let’s add Index View.
For adding Index View just right click inside Index Action Method and choose Add View from the list of the menu after choosing a new dialog will pop up with name Add View in this dialog just choose template “List” and Model class as “CarModel” click on Add button.
Below is a snapshot of Index View which is generated.
Now let’s save code and run the application.
After running application just access URL: - http://localhost:####/Carinformation/Index
After accessing an Index View will appear as shown in below snapshot.
This View will contain data which we have inserted.
Wow, we have pulled data from MongoDB database.
But we have not configured the link in this part, so let’s configure it.
We have assigned object id which is a unique id in MongoDB to id parameter in ActionLink.
READ [Single Document]
In this part, we are going to display single records (Details) according to ObjectId which we choose from index View.
For displaying single records (Details) we are going to use FindOne() method as shown in the below snapshot.
Snapshot of Details ActionMethod
After completing the code snippet now let’s add Details View.
For adding view just right click inside Details Action Method and choose Add View from the list of the menu. After choosing this a new dialog will pop up with name Add View. In this dialog just choose template “Details” and Model class as “CarModel” click on Add button.
Below is a snapshot of Details View which is generated.
Now let’s save the code and run the application.
After running the application just access URL - http://localhost:####/Carinformation/Index
After accessing an Index view will appear as shown in below snapshot.
Then we are going to click on Details button to see Details View.
After clicking on Details button it will call Details Action Method which takes Objectid as input parameter and on basis of that parameter it gets data from MongoDB database to display data.
Details View
After completing with Details View in next part we are going to edit Car record.
EDIT / UPDATE
In this part, we are going to edit records which we have saved in MongoDB database.
For editing records first, we need to get that data from the database to display it; after that we can update the data.
In the below snapshot we are first validating if the document already exists in the database or not by passing ObjectId and getting a count of the document if the count of the document is greater than 0 then the document exists after that we only get data for displaying in Edit mode.
Snapshot of Edit ActionMethod
Code Snippet
-
- public ActionResult Edit(string id)
- {
- var document = _dbContext._database.GetCollection<CarModel>("CarModel");
-
- var carDetailscount = document.FindAs<CarModel>(Query.EQ("_id", new ObjectId(id))).Count();
-
- if (carDetailscount > 0)
- {
- var carObjectid = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));
-
- var carDetail = _dbContext._database.GetCollection<CarModel>("CarModel").FindOne(carObjectid);
-
- return View(carDetail);
- }
- return RedirectToAction("Index");
- }
Now let’s add Edit View.
For adding view just right click inside Edit Action Method and choose Add View from the list of the menu. After choosing it a new dialog will pop up with the name Add View -- in this dialog just choose template “Edit” and Model class as “CarModel” click on Add button.
Below is a snapshot of Edit View which is generated.
Now let’s save code and run the application.
After running application just access URL: - http://localhost:####/Carinformation/Index
After accessing an Index view will appear as shown in below snapshot.
Then we are going to click on Edit button to see Edit View.
Now we have just shown data in edit mode now we need to write code for updating these values to MongoDB database on click of save button. For that, we are going to add another Action Method with same name Edit which will handle [HttpPost] Request.
Update
Snapshot of Edit ActionMethod
Code Snippet
-
- [HttpPost]
- public ActionResult Edit(string id, CarModel carmodel)
- {
- try
- {
- carmodel.Id = new ObjectId(id);
-
- var CarObjectId = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));
-
- var collection = _dbContext._database.GetCollection<CarModel>("CarModel");
-
- var result = collection.Update(CarObjectId, Update.Replace(carmodel), UpdateFlags.None);
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
Now let’s save code and run the application.
After running application just access URL - http://localhost:####/Carinformation/Index
After accessing it, an Index view will appear as shown in the below snapshot.
Then we are going to click on Edit button to see Edit View.
After clicking on Edit button you can see Edit view in Edit Mode. Now in this Mode we are going to update the Color of the Car from Blue to Brown and click on “Save” button to update values.
After clicking on update button this value gets updated in the database and it is redirected to the index page for displaying grid.
Now if we see index view then update value will be displayed.
Wow, we have completed with Updating data in MongoDB.
DELETE
In this part, we are going to delete the record which we have saved in MongoDB database.
For delete records first, we need to get that data from the database to display, and after that we can delete data.
Snapshot of Delete ActionMethod
Now in this process we are first going to open index view from there we are going to click on Delete button then delete action method will get called which take Objectid as input parameter and then we are going to pass this parameter to create mongo query then this query will be passed to GetCollection method to get Car model data.
After adding Action method with name delete which handles HttpGet request now let’s add Delete View to display record to delete.
Now let’s add Delete View.
For adding view just right click inside Delete Action Method and choose Add View from the list of the menu. After choosing it a new dialog will pop up with name Add View in this dialog just choose template “Delete” and Model class as “CarModel” click on Add button.
Below is a snapshot of Delete View which is generated.
Now let’s save code and run the application.
After running the application just access URL - http://localhost:####/Carinformation/Index
After accessing an Index view will appear as shown in below snapshot.
Then we are going to click on Delete button to see Delete View.
After clicking on Delete button you can see Delete view as shown below.
Now we are able to see Delete View but we cannot delete record because we have not added Delete Action Method which will handle HTTP post request Let’s add it.
In this part, we have written code for handling Http post Delete request which is going to take ObjectId as input parameter and in this parameter we are going to pass to create Mongo Query, and this Mongo Query will be passed to Remove Method which will remove this document from the database.
Snapshot of Delete ActionMethod
Code Snippet
-
- [HttpPost]
- public ActionResult Delete(string id, CarModel CarModel)
- {
- try
- {
-
- var carObjectid = Query<CarModel>.EQ(p => p.Id, new ObjectId(id));
-
- var collection = _dbContext._database.GetCollection<CarModel>("CarModel");
-
- var result = collection.Remove(carObjectid, RemoveFlags.Single);
-
- return RedirectToAction("Index");
- }
- catch
- {
- return View();
- }
- }
Now, let’s save the code and run the application.
After running the application, just access this URL: - http://localhost:####/Carinformation/Index
After accessing, an Index View will appear, as shown in below snapshot. Then, we click on Delete button to see Delete View.
After clicking on "Delete" button, the Delete view will be shown as below. Now, just click on Delete button to delete this record from MongoDB database.
Below is the output after deleting the record
Wow! We have finally come to end of the article. Here we have learned how to perform simple CRUD operation with ASP.NET MVC using MongoDB in step by step way.
Thanks for reading this article. I hope it helped you a lot. Share this article if you liked it.
Finally, before winding up, have a look at this MongoChef tool which is a really cool tool for managing Mongo DB Database. I will explore it in upcoming Mongo DB articles.