Click here to Skip to main content
13,259,539 members (53,403 online)
Click here to Skip to main content
Add your own
alternative version

Stats

41.6K views
1.7K downloads
35 bookmarked
Posted 14 Jan 2015

CRUD Operation in MVC with MongoDB

, 14 Jan 2015
Rate this:
Please Sign up or sign in to vote.
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:
    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:
    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:
    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

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

  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:
    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:
    [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()

Retrieve User Data from Mongo DB through LINQ

Add an Action Method to retrieve all the users:

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:

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:
    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:
    [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)

Share

About the Author

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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 4 Pin
Member 1228964512-Feb-17 22:14
memberMember 1228964512-Feb-17 22:14 
QuestionMongoDb with .net Mvc Pin
Member 1290389615-Dec-16 2:27
memberMember 1290389615-Dec-16 2:27 
QuestionHow to connect remote mongodb server ? Pin
Harish_Jain5-Nov-15 2:43
memberHarish_Jain5-Nov-15 2:43 
QuestionBadly out of date Pin
Jacob Johnston10-Oct-15 14:15
memberJacob Johnston10-Oct-15 14:15 
QuestionMissing downloadable code files Pin
Arkadeep De3-Sep-15 4:03
professionalArkadeep De3-Sep-15 4:03 
AnswerRe: Missing downloadable code files Pin
Vijay Rana AON4-Sep-15 5:54
professionalVijay Rana AON4-Sep-15 5:54 
GeneralRe: Missing downloadable code files Pin
Arkadeep De5-Sep-15 20:51
professionalArkadeep De5-Sep-15 20:51 
QuestionCode is not Downloading Pin
Er Himanshu Khudania25-Aug-15 0:29
memberEr Himanshu Khudania25-Aug-15 0:29 
AnswerRe: Code is not Downloading Pin
Vijay Rana AON4-Sep-15 5:58
professionalVijay Rana AON4-Sep-15 5:58 
QuestionDownload has is not working.......... Pin
Ganesh Vellanki15-May-15 22:34
memberGanesh Vellanki15-May-15 22:34 
AnswerRe: Download has is not working.......... Pin
Vijay Rana AON4-Sep-15 5:58
professionalVijay Rana AON4-Sep-15 5:58 
GeneralMy vote of 3 Pin
tforsberg27-Jan-15 9:18
professionaltforsberg27-Jan-15 9:18 
QuestionHelpful Article Pin
UTTAM GOSWAMI21-Jan-15 0:59
memberUTTAM GOSWAMI21-Jan-15 0:59 
Questionsource file cannot be downloadable Pin
fredatcodeproject15-Jan-15 2:28
memberfredatcodeproject15-Jan-15 2:28 
Questionsource code file link broken Pin
Tridip Bhattacharjee14-Jan-15 21:21
memberTridip Bhattacharjee14-Jan-15 21: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 14 Jan 2015
Article Copyright 2015 by VijayRana
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid