Accessing MongoDB via C#

Last week we looked at setting up a MongoDB instance, and working with it through the Mongo shell. This week, we look at accessing it through the C# driver.

Getting the Driver

There are several .NET drivers available for MongoDB. You can check out the list here. I chose to use the mongodb-csharp driver. It seems to to have the widest feature set, and the most support. To use it, you can either build it from the source, or download the binaries directly here.

Using the Driver

To use the driver, simply create a new project and add a reference to it. For our sample, create a new console application. Then right click on references, choose add reference, and find the MongoDB.Driver.dll and add it.


After adding the reference we are ready to write code. Here is a very simple snippet of code to test out Mongo. This is the full content of Program.cs.

using System;
using MongoDB.Driver;

namespace MongoTest
	internal class Program
		private static void Main( string[] args )
			// Connect to the mongo instance.
			var mongo = new Mongo();

			// Use the myorders database.
			Database db = mongo.GetDatabase( "myorders" );

			// Get the orders collection.
			IMongoCollection orders = db.GetCollection( "orders" );

			// Create a new order.
			var order = new Document();
			order["orderAmount"] = 57.22;
			order["customerName"] = "Elmer Fudd";

			// Add the new order to the mongo orders colleciton.
			orders.Insert( order );
			Console.WriteLine( string.Format( "Inserted: {0}", order ) );

			// Create a specification to query the orders collection.
			var spec = new Document();
			spec["customerName"] = "Elmer Fudd";

			// Run the query.
			Document result = orders.FindOne( spec );
			Console.WriteLine( string.Format( "Found: {0}", result ) );

			Console.WriteLine("Press Enter to Exit.");

The comments should explain most of what is happening. One thing worthy of note is the Document class. The Document class is much like a dictionary. Remember that MongoDB does not have a static schema. Therefore a dictionary serves the purpose well since it is dynamic by nature.

There are other drivers (such as NoRM) out there that will map a static C# class into MongoDB much like NHibernate or another ORM, however, then you lose some of the benefit of the dynamic schema, however, depending on your needs, this may be acceptable.

Starting up MongoDB

Note that to use this, you need to have the instance of MongoDB up and running. You can follow the instructions from last week’s post to get it installed. If its already installed, just open a command prompt, go to the bin folder in the install directory (in my case C:\mongodb\bin), and execute the command mogod.


Running the Code

Now you are ready to run the application. Doing so gives the following output.

Inserted: { “_id”: “4bde57114076a60500000001”, “orderAmount”: 57.22, “customerName”: “Elmer Fudd” }

Found: { “_id”: “4bde41cd4076a60df0000001”, “orderAmount”: 57.22, “customerName”: “Elmer Fudd” }

Press Enter to Exit.

Next week we’ll either dive a bit deeper into the driver’s api, or look at the autosharding capabilities of MongoDB. Not sure which yet. See you then!


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

2 Trackbacks

Post a Comment

Your email is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>