Using MongoDB with the NoRM driver

This week we look at using strongly typed C# classes to access a MongoDB database using the NoRM C# driver.

The Driver

The NoRM driver differs from the MongoDB-CSharp driver we looked at last time in that it uses C# classes directly rather than the Document class. It automatically serializes and deserializes your classes to and from JSON. Using it is very similar to using NHibernate or another ORM…hence the name…NoRM.

You can get the driver at: http://github.com/atheken/NoRM

Referencing the driver

To use the driver, simply add a reference to it in your project. For this example, we’ll create a new console app to test out the driver. Add a reference just like you did in the previous example, but this time, you will reference the Norm.dll assembly.

image

The class to persist

We need a class to represent the data we want to persist in the db, so we will create an Order class.

public class Order
{
	public ObjectId ID { get; set; }
	public double OrderAmount { get; set; }
	public string CustomerName { get; set; }
}

This is simple enough.  Now lets look at using the driver.

Connecting the the db

To connect to the database with the NoRM driver, you need to provide the database name, the url, and the port number. Optionally, you can pass in security credentials. In our case, we are not using security, so I just passed in a string.Empty.

var mongo = new Mongo( "myorders", "localhost", "27017", string.Empty );
// For Linq to work, collection name must match Class name.
MongoCollection< Order > collection = mongo.GetCollection< Order >( "Order" );

Getting a reference to the collection

Next we need to get a reference to the collection we want to use. Collections in MongoDB are like tables in an SQL database. To get the collection we call the GetCollection() method on the database. Its a generic method and the generic parameter you pass to it is the type of object stored in that collection.

// For Linq to work, collection name must match Class name.
MongoCollection< Order > collection = mongo.GetCollection< Order >( "Order" );

As a side-note, I found that to get Linq to work correctly, the collection name had to be the same as the class name, but that is beyond the scope of this post. We’ll look at the Linq capabilities of this driver next week.

Inserting a new object into the db

They could not have made it much simpler to insert a new object using this driver. No real explanation is required here.

// Create a new order.
var order = new Order()
            	{
            		OrderAmount = 57.22,
            		CustomerName = "Elmer Fudd"
            	};

// Add the new order to the mongo orders collection.
collection.Insert(order);

The driver handles serializing the order and saving it. One line does it all.

Querying the db

To issue a query, we have two options, we can either create an order object with the properties we want to match on, or we can simply create an anonymous object. Anonymous objects are a bit easier to work with since you don’t have to worry about required properties or default values getting in the way.

Order result = orders.FindOne(new {CustomerName = "Elmer Fudd"});

The FindOne() method on the collection will return a single object. If no object is found, it will return the default value for the collection type.

Updating a document

To update a document, we can either query the object, modify it, and save it; Or we can perform an atomic update on only the fields we want to change. We’ll quickly look at both.

First, here is the query and save code.

// Get the order to change.
var orderToUpdate = orders.FindOne( new {CustomerName = "Elmer Fudd"} );

// Make the change.
orderToUpdate.OrderAmount = 1000000.00;

// Save the changed order.
orders.Save( orderToUpdate );

This is pretty simple. Lets look at updating only a single field atomically…

// Update the OrderAmount.
orders.Update(
		new {CustomerName = "Elmer Fudd"},
		x => x.SetValue( order => order.OrderAmount, 1000000.00 ) );

Here in one statement, we tell MongoDB to update all Orders for customer named Elmer Fudd to be $1,000,000. This statement only modifies that one field. Notice that the code new {CustomerName = “Elmer Fudd”} is the “selector”. That is, the “where clause” of our update statement. Any documents matching the selector will have the SetValue() applied to them.

Well, that’s about all for this week. We’ll probably look into more complex queries next week.

-Chris

This entry was posted in .NET, C#, MongoDB, NoSQL and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment