Getting Started with MongoDB and C#

In C# on February 4, 2010 by jasona

I had been hearing all of this talk of the NoSql movement, and, being the ever-curious tech type, I had to dig in and see what it was all about.

Of all the various options out there, MongoDB has been getting a lot of press lately. MongoDB is hailed as one of the top NoSql options out there for being ultra-scalable, and highly performant. You can see the long list of known production deployments out there.

With that context being set, I had to see what all the excitement was about. And, here’s how you can too:

1.) First, check out the Quickstart to get everything installed and setup. One note here: if you’re like me and you want to setup MongoDB to run as a service, check out the help in “mongod –h” but you can basically run “mongod –-install” and it will install it as a service for you.

2.) Next, go download the MongoDB .NET drivers from:

3.) Unzip, copy where you need to and add it as a reference to your project. You’re all set!

Your next step is to figure out how to work with MongoDB, and, as with any database (relational or not) you still have the basic operations: querying, updating, inserting and deleting.

So, let’s get started!


Connecting to the Server


So, how do we connect? Very simple. Check it out:


This assumes the default host (localhost), and port (27017; unless you configured it differently when setting up mongod). If so, there are constructor overloads to pass in a different host name and port.


Getting the Database


Don’t worry, you’re not in a completely foreign world here. There’s still the concept of a database. Here’s how you get the database instance (carrying forward the earlier code):


Again, simple, right?


Referencing the “Table”


Here’s where it gets interesting. There’s no concept of a table. The idiom to remember here is that MongoDB treats ever record as a “document”. So, instead of a table, there’s a collection of documents. Here’s the fun thing:

Because MongoDB is “schema-free” those documents structure can vary, even when in the same collection.

Yes, hard to twist your brain around, but this is really just a logical grouping of data. In most cases, however, people do put like structured documents into the same collections.

Let’s get our first collection:


In this case, we’re getting a collection called “Contacts”. Even if you’ve never saved anything into that collection, yet, it will still return you a valid collection to work with. So, this is how you create new collections.

Now that we have a collection, we can actually do stuff with it! Exciting, huh?


Introducing the Document: end all, be all.


In the MongoDB world, the Document class is the center of it’s universe. Because the very concept of the database is built upon the concept of this document, this is what you’ll find yourself using most. You use them to insert data, update data, delete data, query data. You will learn to live it, love it and adore the Document.

Here’s where I’m going to pick up the pace a bit because this is really where I got that “Ah ha!” moment, and I think you will to.

First, let’s insert some data:


Here, I did all the stuff from earlier (connecting, grabbing the database, getting the collection), and then I new’ed up a Document object. The Document object is nothing but a big Dictionary object, in this case.

So, I go to town. As you can see, I create a logical entity for a “Contact” in my mind, adding first name, last name, address, city, state and zip code, and I assign values respectively during the process.

Finally, I call the Insert method on my collection, passing in my document.

You have just created your first record in MongoDB. Stop, pat yourself on the back, think to yourself “Really, is that it?” and let’s move on. 🙂

Updating data (and really, pretty much everything else) is just as easy:


Easy! The only difference here (and what I didn’t show) is that I added the “_id” property of my document, after having inserted it earlier. This gives MongoDB reference on which document to update.

Now, deleting is just as easy. In our previous method, we just change the “Update” method to “Delete”. I could also leave the other properties, but in this case I already know the ID, so let’s just strip it down to that:


Again, easy enough!

Now, querying the database. This should look very familiar, and make a lot of sense if you’ve been keeping up:


Here, I create a Document object, I set the “City” property to “Dallas”, and I call Find(), passing in that Document object. The Document object, in this context, acts as the query to MongoDB to tell it what to search for.

From there, I iterate through Find().Documents, which is just a collection of Documents and print out the “FirstName” from each record.

Whew, that was long, sorry. And, there’s still a ton more to cover, but I’ll leave that for another date. Interesting, eh? It’s been enough to make me think about using it in a project myself. What about you?


11 Responses to “Getting Started with MongoDB and C#”

  1. I’ve also been hearing the buzz. One thing I will say is that this would be easier to start with for a complete noob than a relational database. The concept seems much simpler. I’m even more enticed to try it out for myself 🙂

  2. Very cool stuff. Thanks for sharing.

    As you said there is/would be a ton more stuff to cover; but, this got me thinking about after implementation.

    First question that comes to mind for me is, what if you implement this code. I add 100 contact records. And then someone comes along and decides to add “Occupation” to the Contact document in their code. Is this going to effect the existing records? Is MongoDB smart enough to say: 1) no you cannot do that; 2) ok, i’ll go update all the other contact documents to have a null or blank “Occupation” value; 3) does it corrupt the table; 4) or, does it not update the previous records and now when I query the table for “Occupation” i have to account for nulls in code or I crash the database?

  3. @Eric

    Yeah, it’s actually pretty liberating. I remember feeling this same thing with MySql many years ago, and the bonus here is that MongoDB is ultra scalable. Bonus.

    I’ve also built some interesting stuff to simplify and cleanup the patterns with MongoDB that I’m going to be releasing and blogging about soon. Hopefully it would help you even further. 🙂

  4. Nice article. I have been toying around with Mongo and found the Mongdio GUI nice to try the concepts. Have not tried mongoHub but it is also supposed to be good. Both can be found a GitHub.

  5. @Joeld27

    Glad to help!

    Good question! So, if I later introduce a new property to a document in my “Contacts” collection (given my example), you would have to handle for null. But, a quick Convert.ToString() also handles the case well.

    For example:

    foreach (Document item in collection.Find(doc).Documents)
    Console.WriteLine(“Occupation: ” + Convert.ToString(item[“Occupation”]));

    In a later blog post I’ll go a step further and start introducing some best practices and frameworks around using MongoDB.

    In my examples, I use AutoMapper to map my Document back into a POCO, using AutoMappers Converters. In that case, you would have all your transformation logic centralized in one place in your Converter logic.

  6. Very nice article. Thanks for writing it.

    @Joeld27 Mongo is schemaless. Every document you put into it contains information about the schema for that document. If you later add code to start capturing an occupation value in your person document, you have two choices. Make your code handle the possibility that the field may not be there or go the traditional way when working with relational databases and update the existing person records.

  7. @Tim


    Very nice, thanks for pointing me at Mongdio and MongoHub – I’ll definitely check them out! Funny, I was thinking of building something very similar. 😉

  8. @Sam

    Thanks for the compliment! Great work on the driver. Let me know if there’s ever anything I could help with. I would love to contribute, if I can.

  9. Hey Jason, good post. Just wanted to let you know about some work that has been done similiar to your framework I just saw on codeplex. It is very nHibernate like allowing lazy-loaded many-to-one references, type converters, collection mapping (embedded documents for now), and (most importantly) linq support against the poco entities. While it is still well in alpha mode, I’m using it on a production project and it is working out quite nicely. Check out the tests for usage.

    • Very nice, Craig, thanks for giving me a heads up on that!

      Looking at the tests, the implementation looks very clean and sharp. I see you’ve also built in full IoC support, nice!

      Do you have any existing tasks you need done? I’m looking for projects to contribute to.

      re: My project – it’s more for this series of posts, and a place to publish it. 🙂

  10. @Jason,
    The issues tab has some outstanding features that need to be implemented for general consumption. Currently, it is at the state that I needed for my current project, but obviously every project has different needs and I’d like to build something for everyone. 🙂

Comments are closed.

%d bloggers like this: