NoSQL with MongoDB, NoRM and ASP.NET MVC
- by shiju
In this post, I will give an introduction to how to work on
NoSQL and document database with MongoDB , NoRM and ASP.Net MVC 2.
NoSQL and Document Database
The NoSQL movement is getting big attention in this year and
people are widely talking about document databases and NoSQL along with web
application scalability. According to Wikipedia, "NoSQL is a movement promoting
a loosely defined class of non-relational data stores that break with a long
history of relational databases. These data stores may not require fixed table
schemas, usually avoid join operations and typically scale horizontally.
Academics and papers typically refer to these databases as structured storage".
Document databases are schema free so that you can focus on the problem
domain and don't have to worry about updating the schema when your domain is
evolving. This enables truly a domain driven development. One key pain point of
relational database is the synchronization of database schema with your domain
entities when your domain is evolving.There are lots of NoSQL implementations
are available and both CouchDB and MongoDB got my attention. While evaluating
both CouchDB and MongoDB, I found that CouchDB can’t perform dynamic queries and
later I picked MongoDB over CouchDB. There are many .Net drivers available for
MongoDB document database.
MongoDB
MongoDB is an open source, scalable,
high-performance, schema-free, document-oriented database written in the C++
programming language. It has been developed since October 2007 by 10gen. MongoDB
stores your data as binary JSON (BSON) format . MongoDB has been getting a
lot of attention and you can see the some of the list of production deployments
from here - http://www.mongodb.org/display/DOCS/Production+Deployments
NoRM – C# driver for MongoDB
NoRM is a C# driver for MongoDB with LINQ support. NoRM
project is available on Github at http://github.com/atheken/NoRM.
Demo with ASP.NET MVC
I will show a simple demo with MongoDB, NoRM and ASP.NET MVC. To
work with MongoDB and NoRM, do the following steps
Download the MongoDB databse For Windows 32 bit, download from
http://downloads.mongodb.org/win32/mongodb-win32-i386-1.4.1.zip
and for Windows 64 bit, download from http://downloads.mongodb.org/win32/mongodb-win32-x86_64-1.4.1.zip
. The zip contains the mongod.exe for run the server and mongo.exe for the
client
Download the NorM driver for MongoDB at http://github.com/atheken/NoRM
Create a directory call C:\data\db. This is the default
location of MongoDB database. You can override the behavior.
Run C:\Mongo\bin\mongod.exe. This will start the MongoDb
server
Now I am going to demonstrate how to program with MongoDb and
NoRM in an ASP.NET MVC application.Let’s write a domain class public class Category { [MongoIdentifier]public ObjectId Id { get; set; } [Required(ErrorMessage = "Name Required")][StringLength(25, ErrorMessage = "Must be less than 25 characters")]public string Name { get; set;}public string Description { get; set; }}
ObjectId is a NoRM type that represents a MongoDB ObjectId. NoRM will automatically update the Id becasue it is decorated by
the MongoIdentifier attribute. The next step is to create a mongosession class. This will do the all interactions to the MongoDB. internal class MongoSession<TEntity> : IDisposable{ private readonly MongoQueryProvider provider; public MongoSession() { this.provider = new MongoQueryProvider("Expense"); } public IQueryable<TEntity> Queryable { get { return new MongoQuery<TEntity>(this.provider); } } public MongoQueryProvider Provider { get { return this.provider; } } public void Add<T>(T item) where T : class, new() { this.provider.DB.GetCollection<T>().Insert(item); } public void Dispose() { this.provider.Server.Dispose(); } public void Delete<T>(T item) where T : class, new() { this.provider.DB.GetCollection<T>().Delete(item); } public void Drop<T>() { this.provider.DB.DropCollection(typeof(T).Name); } public void Save<T>(T item) where T : class,new() { this.provider.DB.GetCollection<T>().Save(item); } }
The MongoSession constrcutor will create an instance of MongoQueryProvider that supports the LINQ expression and also create a database with name "Expense". If database is exists, it will use existing database, otherwise it will create a new databse with name "Expense". The Save method can be used for both Insert and Update operations. If the object is new one, it will create a new record and otherwise it will update the document with given ObjectId. Let’s create ASP.NET MVC controller actions for CRUD operations for the domain class Category public class CategoryController : Controller{ //Index - Get the category listpublic ActionResult Index(){ using (var session = new MongoSession<Category>()) { var categories = session.Queryable.AsEnumerable<Category>(); return View(categories); }} //edit a single category[HttpGet]public ActionResult Edit(ObjectId id) { using (var session = new MongoSession<Category>()) { var category = session.Queryable .Where(c => c.Id == id) .FirstOrDefault(); return View("Save",category); } }// GET: /Category/Create[HttpGet]public ActionResult Create(){ var category = new Category(); return View("Save", category);}//insert or update a category[HttpPost]public ActionResult Save(Category category){ if (!ModelState.IsValid) { return View("Save", category); } using (var session = new MongoSession<Category>()) { session.Save(category); return RedirectToAction("Index"); } }//Delete category[HttpPost]public ActionResult Delete(ObjectId Id){ using (var session = new MongoSession<Category>()) { var category = session.Queryable .Where(c => c.Id == Id) .FirstOrDefault(); session.Delete(category); var categories = session.Queryable.AsEnumerable<Category>(); return PartialView("CategoryList", categories); } } }
You can easily work on MongoDB with NoRM and can use with ASP.NET MVC applications. I have created a repository on CodePlex at http://mongomvc.codeplex.com and you can download the source code of the ASP.NET MVC application from here