Click here to Skip to main content
15,867,704 members
Articles / Web Development / HTML
Tip/Trick

CRUD Operation in MVC with MongoDB

Rate me:
Please Sign up or sign in to vote.
4.84/5 (23 votes)
14 Jan 2015CPOL2 min read 76.6K   2.5K   38   15
CRUD Operation in MVC with MongoDB

Introduction

This tip is for those who just started working on Mongo DB and have some experience of LINQ.

This post will cover the following topics:

  1. Setup Mongo DB.
  2. Create a User Registration page and save data in Mongo DB.
  3. Retrieve User data from Mongo DB through LINQ.
  4. Delete data from Mongo DB through LINQ.
  5. Edit data in Mongo DB.

Using the Code

Setup MongoDB

  1. Download Mongo DB from the below link:

    http://www.mongodb.org/downloads?_ga=1.20290616.1294468948.1419862328

  2. Set up Mongo DB as per the instructions provided in the below link:

    http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/

Create a User Registration Page and Save Data in Mongo DB

  1. Create an MVC project (I named it MVCWithMongo)
  2. Add a model named UserModel as below:
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace MVCWithMongo.Models
    {
        public class UserModel
        {       
            public object _id { get; set; } //MongoDb uses this field as identity.
    
            public int ID { get; set; } 
    
            [Required]
            public string UserName { get; set; }
    
            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }
    
            [Required]
            [DataType(DataType.EmailAddress)]
            public string Email { get; set; }
    
            public string PhoneNo { get; set; }
    
            public string Address { get; set; }
        }
    }
  3. Add a Controller named UserController:
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MVCWithMongo.Controllers
    {
        public class UserController : Controller
        {
    
        }
    }
  4. Add an Action method named Registration in UserController and add a View:
    C#
    public class UserController : Controller
       {
           public ActionResult Registration()
           {
               return View();
           }
       }
    
  5. Now we are ready with the form and it's time to create a database in MongoDB. If you have already downloaded and configured the MongoDB in step 1, then go to command prompt and start the mongodb.
    C:\Mongodb\bin\mongod.exe 

    In my case, my mongod.exe is located in C:\MongoDB\Bin\.

    If Mongo server is successfully started, then the last line should be:

    Waiting for connection on port 27017

    Image 1

    Don't close the command prompt and run the application.

    Image 2

  6. Download the essential drivers to connect to mongodb from the below link:

    https://github.com/mongodb/mongo-csharp-driver/downloads

    and add the reference of the below libraries in your project:

    using MongoDB.Bson; 
    using MongoDB.Driver;
  7. Add an Action method to post the registration form:
    C#
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using MVCWithMongo.Models;
    using MongoDB.Bson;
    using MongoDB.Driver;
    using MongoDB.Driver.Linq;
    
    namespace MVCWithMongo.Controllers
    {
        public class UserController : Controller
        {        
            public ActionResult Registration()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult Registration(UserModel um)
            {
    
                return View();
            }
        }
    }
  8. Run the application and fill the Registration form and Submit.
  9. Action method for saving data in Mongo DB:
    C#
    [HttpPost]
    public ActionResult Registration(UserModel um)
    {
     //Connect to MongoDB
     MongoServer objServer = MongoServer.Create("Server=localhost:27017");
     //Provide a database name(Mongo server will automatically check a
     //database with this name while inserting.
     //if exist then ok otherwise it will create automatically create a database)
     MongoDatabase objDatabse = objServer.GetDatabase("MVCTestDB");
     //Provide a table Name(Mongo will create a table with this name.
     //if its already exist then mongo will insert in this table otherwise
     //it will create a table with this name and then Mongo will insert)
     MongoCollection<BsonDocument> UserDetails = objDatabse.GetCollection<BsonDocument>("Users");
     //Insert into Users table.
     UserDetails.Insert<UserModel>(um);
     return View();
    }
    
  10. To check the database, open the mongo.exe (In my case, it is in C:\Mongodb\bin\).

    To see all the databases in Mongo Db, use the below query:

    > show dbs 

    To see all the tables (Collection in case of Mongo DB), use the below command:

    > use MVCTestDB 
    > show collections

    To find all the records in Users collection, use the below query:

    > db.Users.find() 

    or:

    > db.Users.find().toArray()

    Image 3

Retrieve User Data from Mongo DB through LINQ

Add an Action Method to retrieve all the users:

C#
public ActionResult GetUsers()
{
    MongoServer objServer = MongoServer.Create("Server=localhost:27017");
    MongoDatabase objDatabse = objServer.GetDatabase("MVCTestDB");
    List UserDetails = objDatabse.GetCollection("Users").FindAll().ToList();
    return View(UserDetails);
}

Delete User Data from Mongo DB through LINQ

Add an ActionMethod for Delete Users:

C#
public ActionResult Delete(int id)
       {
           MongoServer objServer = MongoServer.Create("Server=localhost:27017");
           MongoDatabase objDatabse = objServer.GetDatabase("MVCTestDB");
           IMongoQuery query = Query.EQ("ID",id);
           objDatabse.GetCollection("Users").Remove(query);
           return View();
       }

Update User Data from Mongo DB through LINQ

  1. Add an ActionMethod for Edit Users:
    C#
    public ActionResult Edit(int id)
           {
                 MongoServer objServer = MongoServer.Create("Server=localhost:27017");
               MongoDatabase objDatabse = objServer.GetDatabase("MVCTestDB");
               IMongoQuery query = Query.EQ("ID", id);
               UserModel user = objDatabse.GetCollection("Users").Find(query).SingleOrDefault();
               return View(user);
           }
    
  2. Add an ActionMethod for Post after Edit:
    C#
    [HttpPost]
           public ActionResult Edit(UserModel um)
           {
               MongoServer objServer = MongoServer.Create("Server=localhost:27017");
               MongoDatabase objDatabse = objServer.GetDatabase("MVCTestDB");
               IMongoQuery query = Query.EQ("ID", um.ID);
    
               IMongoUpdate  updateQuery = Update.Set("UserName",
               um.UserName).Set("Password", um.Password).Set("Email", um.Email).Set
               ("PhoneNo", um.PhoneNo).Set("Address", um.Address);
               UserModel user = objDatabse.GetCollection("Users").Find(query).SingleOrDefault();
               objDatabse.GetCollection("Users").Update(query, updateQuery);
               return RedirectToAction("GetUsers");
           }
    

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Hi Myself Vijay having around 7 years of experience on Microsoft Technologies.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Loki Alice12-Feb-17 21:14
Loki Alice12-Feb-17 21:14 
QuestionMongoDb with .net Mvc Pin
Member 1290389615-Dec-16 1:27
Member 1290389615-Dec-16 1:27 
QuestionHow to connect remote mongodb server ? Pin
Harish_Jain5-Nov-15 1:43
Harish_Jain5-Nov-15 1:43 
QuestionBadly out of date Pin
Jacob Johnston10-Oct-15 13:15
Jacob Johnston10-Oct-15 13:15 
QuestionMissing downloadable code files Pin
Arkadeep De3-Sep-15 3:03
professionalArkadeep De3-Sep-15 3:03 
The files are missing in the download link.

AnswerRe: Missing downloadable code files Pin
VijayRana4-Sep-15 4:54
professionalVijayRana4-Sep-15 4:54 
GeneralRe: Missing downloadable code files Pin
Arkadeep De5-Sep-15 19:51
professionalArkadeep De5-Sep-15 19:51 
QuestionCode is not Downloading Pin
Er Himanshu Khudania24-Aug-15 23:29
Er Himanshu Khudania24-Aug-15 23:29 
AnswerRe: Code is not Downloading Pin
VijayRana4-Sep-15 4:58
professionalVijayRana4-Sep-15 4:58 
QuestionDownload has is not working.......... Pin
Ganesh Vellanki15-May-15 21:34
Ganesh Vellanki15-May-15 21:34 
AnswerRe: Download has is not working.......... Pin
VijayRana4-Sep-15 4:58
professionalVijayRana4-Sep-15 4:58 
GeneralMy vote of 3 Pin
tforsberg27-Jan-15 8:18
professionaltforsberg27-Jan-15 8:18 
QuestionHelpful Article Pin
UTTAM GOSWAMI20-Jan-15 23:59
UTTAM GOSWAMI20-Jan-15 23:59 
Questionsource file cannot be downloadable Pin
fredatcodeproject15-Jan-15 1:28
professionalfredatcodeproject15-Jan-15 1:28 
Questionsource code file link broken Pin
Tridip Bhattacharjee14-Jan-15 20:21
professionalTridip Bhattacharjee14-Jan-15 20:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.