NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

 Source Code - http://mongomvc.codeplex.com

 NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 2

 

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 the list of production deployments from here


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

  1. 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
  2. Download the NorM driver for MongoDB at http://github.com/atheken/NoRM
  3. Create a directory call C:\data\db. This is the default location of MongoDB database. You can override the behavior.
  4. Run 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 and persistance to the MongoDB using the NoRM.

 

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 and controller actions for handling CRUD operations for the domain class Category

 

public class CategoryController : Controller

{

 

//Index - Get the category list

public 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 where you can download source code of the ASP.NET MVC application.

 

Published Friday, April 16, 2010 1:16 AM by shiju
Filed under: , ,

Comments

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC

Saturday, April 17, 2010 2:33 PM by davetiye

thank you wery much

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, April 23, 2010 4:13 AM by Kacey Jone

nice post, really have informative information, thanks for publishing this post..

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, April 23, 2010 5:20 AM by Fat Burning Furnace

thanks for sharing such valuable information in regards of NoSQL with MongoDB,hopefully it will be beneficial to others also...

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, April 23, 2010 5:31 AM by Fiona Smithe

Useful information, many thanks to the author. It is puzzling to me now, but in general, the usefulness and significance is overwhelming. Very much thanks again and good luck!

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, April 27, 2010 1:29 PM by paul.vencill

Thanks for sharing this.  When I try to use your MongoSession class above with the latest drop of the NoRM project, though, upon trying to save a new object it looks like the Save method is no longer supported.  When I change the code to use Update instead, I get an exception that "The method equals is not supported".

Thoughts?

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, April 27, 2010 1:54 PM by paul.vencill

Nevermind, found out it wasn't the Update that was causing the problem, it was my subsequent query, which used SingleOrDefault which apparently isnt' well supported yet.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, May 11, 2010 4:02 PM by Alexander DiMauro

There seems to be an issue with the latest NoRM build. In the MongoSession, the MongoQueryProvider() no longer accepts a string as an argument.

Message:

Argument type 'string' is not assignable to parameter type 'Norm.Mongo'

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, May 12, 2010 5:32 AM by shiju

In the new NoRM build, MongoQueryProvider class requires Mongo object as an arguement.

var mongo = new Mongo("Expense", "localhost", "27017", "");

this.provider = new MongoQueryProvider(mongo);

Check out http://mongomvc.codeplex.com/ for the latest update.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, May 13, 2010 7:58 PM by Phil

Hi Shiju,

This is great and NoSQL DBs are a hella fun to play with and all, but unless you're paying for a virtual private server, I understand that it's practically impossible to deploy an application into production use on shared hosting.

How would you deploy this example if your web host does not provide CouchDB or MongoDB services and you were on a shared hosting plan?

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, May 13, 2010 10:53 PM by shiju

@Phil - One alternative approach is using an external MongoDB hosted service like MongoHQ [ https://mongohq.com/home ].MongoHQ is a cloud-based hosted database solution that allows you to quickly and easily create and get your apps up and running with MongoDB

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, June 7, 2010 4:23 AM by Javerter

Does anyone have any experience in comparing MangoDB and CouchDB

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, June 7, 2010 5:38 AM by shiju

@Javerter - Have look at the link  www.mongodb.org/.../Comparing+Mongo+DB+and+Couch+DB

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, June 9, 2010 9:10 AM by Javerter

Thanks Shiju, Perfect

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, June 21, 2010 9:11 PM by reww

Thanks for this ShiJu :)

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, June 22, 2010 11:36 AM by Fat Burning Furnace Review

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any ways ..Keep up your good work.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, June 22, 2010 11:39 AM by Fat Burning Furnace Review

I have really enjoyed reading your blog posts. Any ways ..Keep up your good work.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, June 22, 2010 11:40 AM by Fat Burning Furnace Review

Thanks Shiju, Perfect

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, July 1, 2010 6:32 AM by Divyesh

Please help me,

While Writing a query with join My two table contains Same column name,

it gives me ambiguous error,

M not getting the exact method to give a alias of one of the column

Thanks .....

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, July 1, 2010 10:55 AM by Fat Burning Furnace Scam

Thats a perfect solution! Thanks!

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, July 23, 2010 10:36 PM by Alvin George

This great:) Thank you very much Shiju. your friend Alvin

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, August 11, 2010 6:59 AM by Fast Track Cash

I just stumbled upon your blog and required to say that I have genuinely enjoyed studying your web site posts. Any way I'll be subscribing to your feed and I hope you submit once more quickly.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, August 11, 2010 7:21 AM by Grow Taller 4 Idiots

I have not been on this webpage in a long time... however it was another joy to see It is such an important topic and ignored by so many, even professionals. I thank you to help making people more aware of possible issues.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, August 11, 2010 7:44 AM by Rocket Piano

Loving this the post as it is in reality the sweetest on this valuable topic. I agree with your conclusions and will thirstily look forward to your upcoming updates. Saying thanks will not just be enough, for the wonderful clarity in your writing. I will at once grab your rss feed to stay informed of any updates

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, August 23, 2010 6:56 AM by Mark Little

thanks for sharing such valuable information in regards of NoSQL with MongoDB.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, October 21, 2010 10:48 AM by Alex

Hi,

Does this support lazy loading of any kind?

For example, if I had a model along the lines of a forum (question / answer posts) - could i lazy-load the answers on a question object?

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, October 22, 2010 11:19 AM by Kenny

Just downloaded the latest MongoDB and NoRM driver, having this error when using your Session class: "Norm.Linq.MongoQueryProvider" is inaccessible due to its protection level."

Any idea why? Thanks.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Saturday, October 23, 2010 7:57 AM by shiju

@Kenny - NoRM is updated and willl update my demo app with the latest NoRM driver

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, October 29, 2010 4:28 AM by davetiye

Very Nice ! Thanks…..

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, December 17, 2010 9:30 AM by Greg Plummer

This information is very useful

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, February 18, 2011 6:23 AM by Muğla

NoRM is updated and willl update my demo app with the latest NoRM driver..

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, April 8, 2011 11:05 AM by Olive Garden Coupons

many thanks sharing these useful data with reference associated with NoSQL by using MongoDB,ideally it'll be best to other folks additionally...

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, April 13, 2011 12:45 AM by save my marriage today review

Mysql is the way to go. Nosql or mongobd is just temporary.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Saturday, April 16, 2011 9:49 AM by Tahari Suits

Gracias a la gente de la comunidad ALT.NET Hispano, pude participar de una VAN (des-conferencia) sobre

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, May 10, 2011 10:35 PM by Buy Capsiplex

very nice and interesting post. i like the way you express every point.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, May 26, 2011 5:28 AM by Joann Fabrics Coupons

I just stumbled upon your blog and required to say that I have genuinely enjoyed studying your web site posts. Any way I'll be subscribing to your feed and I hope you submit once more quickly.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, May 27, 2011 2:24 AM by Save my marriage today review

Thanks for the code. The way u have explained it is pretty simple and it really brushed my concepts well once again. Useful, would surely look for your new posts

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, June 1, 2011 7:46 AM by KIRIKKALE HABERLERI

Thanks code beatiful

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, June 2, 2011 9:11 PM by Joann Fabrics Coupons

You certainly gave a great perception on exactly how this whole process works.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, June 7, 2011 8:39 PM by Lane Bryant Printable Coupons

Mysql is the way to go. Nosql or mongobd is just temporary.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, June 16, 2011 11:55 PM by how to get rid of bed bugs

Thanks so much for the explanation and particularly for the source code of your example, which was particularly useful.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, July 7, 2011 11:03 AM by Ex2 system scam

NoSQl it look it could of great help. I usually like to work with database and I think I can make use of it.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, July 11, 2011 8:28 PM by huntington beach chiropractor

NoSQL implementations are available and both CouchDB and MongoDB got my attention

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, August 2, 2011 1:27 PM by İzmir Davetiye

many thanks sharing these useful data with reference associated with NoSQL by using MongoDB,ideally it'll be best to other folks additionally...

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, September 9, 2011 1:33 PM by davetiye

very nice blog and work

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, November 1, 2011 11:11 AM by izmir davetiye

very nice blog and work

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, November 8, 2011 4:36 PM by Guzeldavetiye

You're great.Thank you very much.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, November 9, 2011 8:47 AM by Kırıkkale Haber

Very nice blog asp.net beatifull

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Sunday, November 13, 2011 1:09 PM by davetiye

thank you very much

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, December 13, 2011 5:19 AM by Davetiye

thank you very much

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Monday, February 13, 2012 4:59 PM by nikah şekeri

really a great resource.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Thursday, April 12, 2012 12:37 PM by Davetiye

I was looking for a source like that. Then i found this post. Thanks for your share.

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Wednesday, June 27, 2012 8:21 PM by davetiye-dukkani

a useful platform for sharing good work ..

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, September 28, 2012 5:01 PM by Sizemore

Saved as a favorite, I like your blog!

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Tuesday, October 16, 2012 7:31 AM by Mackenzie

Thanks for finally talking about >NoSQL with MongoDB, NoRM and ASP.

NET MVC - Part 1 - Shiju Varghese's Blog <Loved it!

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Friday, November 30, 2012 6:57 AM by Davetiye

Thats a perfect source. I was looking for something like that and it corresponded all my needs. thanks

# re: NoSQL with MongoDB, NoRM and ASP.NET MVC - Part 1

Sunday, February 23, 2014 10:09 AM by muhasebe programı

code beautiful

Thanks

Leave a Comment

(required) 
(required) 
(optional)
(required)