Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

CRUD Operation in MVC with MongoDB

0.00/5 (No votes)
14 Jan 2015 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here