MongoDB and ASP.NET MVC – A basic web app

January 16th, 2011 / Comments

I first heard about document databases (NoSql) last year thanks to Rob Conery’s blog post. At the time I couldn’t imagine a database without SQL but there really is such a thing and MongoDB is a leading example. Today I’ve spent some time working with MondoDB putting together a basic ASP.NET MVC web application to CRUD a bugs database.

A document database differs from a relational database in that, when you can get away with it, a record (known as a document here) can contain all it’s own data. It is not necessary to have normalised tables with joins pulling data together into a result set. Instead of having an order table, a product table, a customer table, an address table etc… you can have a single record containing all this information.

Here is an example of a single record for a user :

	{
    "name": "Mr Card Holder",
    "email": "[email protected]",
    "bankAccounts":
    [
        {
            "number": "12332424324",
            "sortCode": "12-34-56"
        },
        {
            "number": "8484949533",
            "sortCode": "11-33-12"
        },
    ],
    "address":
    {
        "address1": "100 The Big Road",
        "address2": "Islington",
        "address3": "London",
        "postCode": "LI95RF"
    }
}
	

And that’s how the record is stored in the database; the exact opposite of a normalised database. The user’s bank accounts are stored in the user document. In this example a user’s bank accounts are unique to that user so it’s ok to store them right there. But what about when the associated information needs to be more centralised such as an author’s list of published books? What happens when there are multiple authors on a book? In this case you would have a separate collection for the books and put the list of book ObjectIds in the author document. Like this :

	{
    "name": "Mr Author",
    "email": "[email protected]",
    "publishedBooks":
    [
        {"id": "12332424324"},
        {"id": "5r4654635654"},
        {"id": "5654743"}
    ],
    "address":
    {
        "address1": "142 The Other Road",
        "address2": "Kensington",
        "address3": "London",
        "postCode": "L92RF"
    }
}
	

After loading the author from MongoDB you would then perform a second query to load the associated books.

The data is stored in BSON format (a binary format of JSON). You still get indexes and the equivalent of where clauses, the simplicity is not at the cost of functionality. Pretty much the only thing you don’t get are complex transactions.

I wanted to try this out for myself so I installed MongoDB and saw it working from the command line and then started looking into a C# driver. After a quick look around the internet it seems that there are two main options for C# drivers :

I chose the official driver because, although it isn’t as mature as Sam Corder’s driver, I’d already started reading the docs for it.

A day in Visual Studio and a JSON Viewer

First I wrote a very rudimentary membership provider that uses the Mongo database. This lets you register on the site and then login which is enough for my test. Hopefully the MongoDB guys will release a complete ASP.NET membership provider soon.

Secondly I wrote an ASP.NET MVC controller, domain class and MongoDB bug repository to help me figure out how to work with a Mongo database using C#. The BugRepository class contains database code like this :

	public Bug Read( string sId)
{
    MongoServer oServer = MongoServer.Create();
    MongoDatabase oDatabase = oServer.GetDatabase( "TestDB");
    MongoCollection aBugs = oDatabase.GetCollection( "bugs");
 
    Bug oResult = aBugs.FindOneById( ObjectId.Parse( sId));
 
    return oResult;
}
 
public Bug Update( Bug oBug)
{
    MongoServer oServer = MongoServer.Create();
    MongoDatabase oDatabase = oServer.GetDatabase( "TestDB");
    MongoCollection aBugs = oDatabase.GetCollection( "bugs");
 
    aBugs.Save( oBug);
 
    return oBug;
}
	

If, like me, you are just getting started using MongoDB with C# you may find it useful to see the code so here is the source code for the test app. You’ll need Visual Studio 2010 and MVC 3. This is what you’ll get :

My main resources while figuring this out were :

One more thing. Document databases are absolutely perfect for content management systems. One of the challenges for a CMS is handling dynamic schemas and in relational databases this usually involves at least two generic looking tables. To a document database the collection schema is a trivial concept, it just doesn’t care! You can add new properties to a collection whenever you feel like it, even when there is huge amount of data already there. Drupal has already integrated MongoDB I expect more to follow.

ASP.NET MVC , MongoDB

Comments