Step 1: Let’s start with MongoDB server installation for our application. In this application I am using MongoDB 3.0.4 server. The following image indicate the installation of server. Setup files downloaded from MongoDB official website.
Step 2: Now it’s time to check server has installed properly or not on machine. So go to location ‘C:\Program Files\MongoDB\Server\3.0\bin’. After successful installation of server bin folder contains the following mentioned files.
Step 3: Start MongoDB.
To start MongoDB, execute the following from the command prompt: C:\ProgramFiles\MongoDB\Server\3.0\bin\mongod
This will start the main MongoDB database process. Now waiting for connections message in the console. Output indicate that mongod.exe running successfully.
Step 4: Connect to MongoDB in order to perform database operations
Run command from new command prompt: C:\Program Files\MongoDB\Server\3.0\bin\mongo
Execute command ‘show dbs’ – it shows a list of database present at server.
MVC Application with MongoDB
MVC Application UI: We are going to design the following user interface using MVC & all CRUD operations are performed using MongoDB database, so all the methods which we are going to use are with respect to MongoDB database syntax.
Application Folder & File Structure are as follows:
UserRepositary Model Class File: We are going to use this model class to perform CRUD operation in MongoDB database.
Create Application Database
- using MongoDB.Bson;
- using MongoDB.Driver;
- using MongoDB.Driver.Builders;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MvcRegistration.Models
- {
- public class UserRepositary : IUserRepositary
- {
- ObjectId id = new ObjectId();
-
- MongoClient client = null;
- MongoServer server = null;
- MongoDatabase database = null;
- MongoCollection UserDetailscollection = null;
-
- string connectionString = "mongodb://localhost";
- private List<UserModel> _UserList = new List<UserModel>();
-
- public UserRepositary()
- {
- try
- {
- client = new MongoClient(connectionString);
-
- server = client.GetServer();
-
- database = server.GetDatabase("MVCDB");
-
- UserDetailscollection = database.GetCollection<UserModel>("UserModel");
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- }
Above code will create 'MVCDB' database at MongoDB server.
We can test weather database is created or not using command '
show dbs'.