Monday, February 17, 2014

MongoDB with MVC4 Web-API C#

Mongo db is a document oriented database. Mongo db has a free and commercial version. It is scalable, open source and document oriented. All Nosql db are document oriented mostly.  Main data base types are RDBMS, OLAP & NoSql. NoSql db are for Big data store and faster access. It is scalable. Scalable means db can be stored in commodity computers, so NoSql databases is horizontal scalable. (Hadoop).

NoSql has mainly 3 types-
1>Key-Value, 2> Tabular, 3> Document Oriented. Mongo is document oriented NoSql Db. NoSql does not have relations. It does not support complex database. But the features are there is - Fast Performance, Query-able, scalable.  In brief, NoSql is for performance, RDBMS is for functionality, though it is not cent right from all aspects.
In case of Mongo, collections are same as tables in RDBMS. Table has recorded in row. But in mongodb stores document (BSON) in collection.

Example-
{_id:”123”, name:”subhadip”,address:”agarpara”},{_id:”124”,name:”nemo”,addresses:[{address:”add1”},{address:”add2”}]}

You can see an unstructured data collection.

Now , query to extract data from collection is there in No-Sql.
Example- db.employee.find({name:”subhadip”});

Indexing is possible in MongoDB. Ad hoc queries like- search by field, regular expression can be used. Distributed database supported in mongodb. Load-balancing is a build in feature. Mongodb has file storage functions available (GridFS). Aggregation in MongoDB is possible using map reduce. Mongo db understands longitude and latitude in its own. For business logics no need to convert record to object, it is already structured as object in code.

It supports almost all popular OS (Windows, Linux, Mac, etc).

Now lets jump to code using MVC 4, C#, MongoDriver.
Create a db in mongo called company and it should have a collection -employees.[_id,Name,Address](_id will be auto generated).
Create DB Command- >use Company (enter)
Create Collection Command->  db.Employees.insert({Name:'Subha',Address:'agarpara;}) (enter)

Install MongoC#Driver from Add Libary Package Reference
Ok, Lets start coding.
First , Create Model-
    public class Employee
    {
        [ScaffoldColumn(false)]
        [BsonId]
        public ObjectId EmpId { get; set; }

        [ScaffoldColumn(false)]
        public string Name { get; set; }

        [ScaffoldColumn(false)]
        public string Address { get; set; }
    }

Now , Create MongoDBContext-
public class MongoDBCS
    {
        public MongoDatabase db;
        public MongoDBCS()
        {
            var con =
                new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDBString"].ConnectionString);

            var server = MongoServer.Create(con);
             db = server.GetDatabase(con.DatabaseName);
        }

        public MongoCollection<Employee> Employees
        {
            get
            {
                return db.GetCollection<Employee>("Employees");
            }
            set { }
        }

    }

Now, Create controller(API)-
public class EmployeeController : ApiController
    {
        private MongoDBCS MongoContext;

        public  EmployeeController()
        {
            MongoContext = new MongoDBCS();
        }
        // GET api/employee
        public IEnumerable<Employee> Get()
        {
         
            var el = MongoContext.Employees;
            return el.FindAll();
        }

     

        // POST api/employee
        public void Post(Employee emp)
        {
            var el = MongoContext.Employees;
            el.Save(emp);
        }


        // DELETE api/employee/5
        public void Delete(string name)
        {
            var el = MongoContext.Employees;
            el.Remove(Query.EQ("Name", name));
        }
    
    }

Web.config will have db connection string –
<add name="MongoDBString" connectionString="server=127.0.0.1;database=company" />

That’s it.Now, You know how to work with MongoDB and C# MVC4.


No comments: