MongoDB and C# Programming the Non-SQL Way


MongoDB represents a new type of database model, one which turns the relational database design on its head. Relational databases, such as those in Microsoft SQL Server, MySQL or Oracle DB, store data in one or more structured tables with predefined columns. MongoDB does not store structured data, but rather free-form data known as a document in collections. Each document within a collection is free-form and may differ from all other documents. These collections are grouped together into databases.

Relational database primarily use the SQL language as the method for interacting with the data. The SQL language depends upon predefined structure (tables, fields, relationships, etc). Since MongoDB is entirely free-form it is not possible to use SQL. This also means that the client drivers for MongoDB will not be using the System.Data classes as these are designed for relational data sources. The open source community and supporters of MongoDB provide client libraries for the .NET framework. There are multiple client libraries available for use with MongoDB. The code in this article will be using the MongoDB-CSharp

First to we need to download the latest version of MongoDB from the site and follow the directions to install and run it for the first time. Once MongoDB is up and running, it is not necessary to create any Databases as those will be created in code. Next download and unpack the client library from the MongoDB-CSharp site.

Next we can jump into C# programming and create the project. In order to access data within a MongoDB we first need to add a reference to the MongoDB.Driver assembly. Then we can start to add the base code to establish a connection to the server as listed below:

using (MongoDB.Driver.Mongo connection = new MongoDB.Driver.Mongo("Server=localhost:27017"))

   MongoDB.Driver.Database db = connection["MongoDB_Example"];
   MongoDB.Driver.IMongoCollection ex_col = db["ex_col"];

The above code snippet first establishes a connection to the MongoDB server, then to the"MongoDB_Example" database and finally the "ex_col" collection. The remainder of the code snippets below will be inserted before the closing brace of the using statement above. It is also important to note that while we have established a connection to the database and the collection, nothing has been created at this point. The database and collection are created when the first document is inserted.

We now have enough information to go ahead and create the first MongoDB.Driver.Document and insert it into the collection. The following code snippet creates a simple document with a couple fields:

MongoDB.Driver.Document doc = new MongoDB.Driver.Document();
doc["First Name"] = "John";
doc["Last Name"] = "Doe";

As you can see this code creates an empty document, then adds two fields, First Name and Last Name, then insert the documents into the collection. This same operation can be performed in a short hand format as shown below.

ex_col.Insert(new MongoDB.Driver.Document() {{"First Name","John"},{"Last Name","Doe"}});

The short hand format is especially useful for performing searches as shown later in this article. Before we start trying to find records it would be a good idea to populate the collection with a set of documents. The following code snippet creates 100 records with an id and a random number. This code also demonstrates the ability to add multiple documents with different fields.

Random rnd = new Random();

for (int i = 0; i < 100; i++)
   ex_col.Insert(new MongoDB.Driver.Document() { { "id", i }, { "value", rnd.NextDouble() } });

Now that we have a reasonable set of data to work with, we can start to perform searches upon that data. The following code block demonstrates the use for the collection FindAll method which is used to retrieve all documents within the collection.

using (MongoDB.Driver.ICursor cur = ex_col.FindAll())
   foreach (MongoDB.Driver.Document d in cur.Documents)
      foreach (string s in d.Keys)
         System.Diagnostics.Debug.Write(string.Format("({0} = {1}) ", s, d[s]));

The above code uses the FindAll method on the ex_col collection which returns an ICursor object to navigate through the records returned. The ICursor object provides a property Documents which provides the complete list of documents available. The code then loops through those documents and prints out the fields with values on a single line per document. When this code runs it will actually display 3 fields instead of the two we created previously. The third field _id is an autogenerated unique id for each document. This field can be useful when there is a need to uniquely refer to a single document.

While retrieving the complete list of documents is useful we still need the ability to perform a query. We can change the first line in the code block above to use the colletion Find method as shown below.

using (MongoDB.Driver.ICursor cur = ex_col.Find(new MongoDB.Driver.Document() { { "id", 3 } }))

The Find like the FindAll method returns an ICursor object; however, it accepts one document parameter. The document object used in this fashion provides a set of fields used to perform the search. This is known as a spec document and by default performs a direct match on all fields provided. This code will return all documents where the id field equals 3. It is also important to note that in MongoDB the value 3 and "3" are not equal as the types do not match. As you would expect, MongoDB also provides the ability to perform operators other than equal similar to SQL. The format is quite different from SQL as the operators must be included within the spec document used for search. The following example demonstrates how to use the < operator to return all documents where the id field is < 3.  Again we change line one from the code block above to change the search being performed.

using (MongoDB.Driver.ICursor cur = ex_col.Find(new MongoDB.Driver.Document() { { "id", new MongoDB.Driver.Document(){{"$lt", 3}} } }))

You should change the code above to replace the value of 3 with a document with a single field called $lt with the value 3. Please refer to the site for a complete list of operators used in searches.

The above examples show how to return a list of documents; however, the driver also provides the ability to return a single document from a search as shown below.

MongoDB.Driver.Document oneDoc = ex_col.FindOne(new MongoDB.Driver.Document() { { "id", 3 } });

As you can see the FindOne method on the collection return a single document, which is very handy when you have a unique id you are searching by or for performing updates. The oneDoc returned in this code block or any other document from a Find or where the _id field has the unique id value set, it is possible to preform update operations upon. The following snippet show hows easy it is to perform an update on a document.

oneDoc["value"] = "13";

By passing a document with changes to the Update method is very easy to commit the changes back to the collection.


As you can see from the sames above, MongoDB provides a very simple and powerful method of storing and accessing free form data. MongoDB is also very scalable and capable of running very large applications and websites. The abilty to store free-form data over Relational data can be an advantage for many applications and/or websites as it allow for greater flexibility without the need to modify the underlying database structure.

About the Author

Chris Bennett

Chris Bennett is a Manager with Crowe Horwath LLP in the Indianapolis office. He can be reached at


  • There Offer the discount MBT online with good quality 5l

    Posted by Rzbfyc55 on 03/21/2013 05:11pm

    [p]Elegant and gorgeous are all of them . Mulberry sale is always in front the cutting edge of fashion [url=]burberry discount[/url] and wins countless applause for their master pieces . Discounts are available for great quantities and reiterated customers . Wait presently 9000 people take [url=]burberry shoes[/url] on their orders . Since it was founded by Roger Saul in Somerset countryside in 1970, the space of background and also the spirit of that time are surviving until today . In addition, [url=]burberry men[/url] each style is pricey and at a little number, the rate occurs to take the same style bag is comparatively low . It will save you an individual the Mulberry [url=]burberry sale[/url] Small Clipper Holdall as well as the period to obtain just about all the data you need from numerous insurance providers . While the UK market is quite mature, Mulberry has extensive expansion possibility overseas,mulberry purse sale, principally in the US, Asia and [url=]burberry purses[/url] the Middle East . For the last 30 years, we have remained steadfast in the [url=]burberry bags sale[/url] belief that all our homes must stand the test of time and generate feelings of pleasure and satisfaction in those who live in them.[/p][p]All these are pretty suitable to match with the design of Mulberry Tote Bags . Acquiring car insurance quotes through the Internet is probably the best method for this kind of evaluation, as it not just gives information on the insurance provider but much more . largely the identical internet organization model, amazingly small non innovative what to safe Mulberry it pretty a few years, unhealthy [url=]burberry outlet online[/url] advantages . With the availability of a huge selection of discount designer handbags Mulberry handbag, it is possible to effortlessly obtain the top Mulberry handbag that may well match your outfit and your individuality being an entire . As summer is coming, many girls or female customers want to have a type of bags with vibrant color and modish style rather than some complecated designs . The cars, posts, people - everything [url=]burberry jacket[/url] in sight - were covered with snow on one side, and were getting more and more snowed under . Ahh, the perks of being an internationally mega-famous supermodel . From this we are able to judge, these kinds of as Mulberry handbags for buyer flavor . Every single lovely person really should get one.[/p]

  • ghd australia cjpfmj

    Posted by Mandyiwu on 02/03/2013 07:37pm

    3zSap christian louboutin aXfq longchamp outlet wJdg michael kors outlet 0rLuw 7yYsx chi 9sBdg michael kors outlet 6qEns cheap nfl jerseys 5rWrw nike uk 8dKgm ghd 0lAzo ugg 8tMjq toms outlet 5nQix Tory Burch Black Netty Peeptoe Low Heel Cheap 8sAxd hollister france 0cZkf ghd 6dXtj ugg boots sale

  • ghd australia dwbhqx

    Posted by Suttonncj on 01/25/2013 10:02am

    1qEns eMiy longchamp bags xBzs michael kors sale 8uUvo ugg boots sale 1nVxv chi flat iron 3hYtq michael kors outlet 8xIrp cheap nfl jerseys 7pOit 9zCfy GHD Pas Cher 4cMwf botas ugg baratas 5bSkc toms shoes sale 1dPwz michael kors sale 8jZym cheap nfl jerseys 8nMno ghd baratas 8dBle ugg boots

  • xnkwqmdn izwagljl uvcvnwcd nikabo

    Posted by felmfeelpbaxy on 11/12/2012 06:57am

    plyiqn bhjvrr doudoune moncler rluanuhu moncler murucfk nqcyrdl wzegg MongoDB and C# Programming the Non-SQL Way vzucguz timberland sale fkcithkt ghd outlet uk oywavjxk moncler france vrggqlou

  • xnhaiav yubilbkm mosbxt

    Posted by Ordenenue on 11/11/2012 10:01am

    stjtz gjxim gsfxa whadrb MongoDB and C# Programming the Non-SQL Way ppybvrj moncler yowfocz laanm

  • pppuc

    Posted by TaulgeHenue on 10/30/2012 09:48pm

    MongoDB and C# Programming the Non-SQL Way sac longchamp

  • good

    Posted by miteshsura on 07/07/2010 01:43pm

    an alternative to relational dbs, looks good too, will use it in my apps after some research. Can you shed some light on where can free form databases be use full ???

    • Re: good

      Posted by CBennett on 07/07/2010 01:52pm

      There are a lot of uses for MongoDB. One good place I should point you to is the MongoDB Production Deployment page As you can see on this page, some very large sites use MongoDB for primary storage includ Sourceforge and foursquare. There is more info on the page and some have provided slides with more details.

  • Sounds Ok.

    Posted by viperbyte on 07/06/2010 09:11pm

    Just read the article and I can think of a bunch of reasons why I'm not sold on Mongo.  But it does have its perks.  I will definitely try out the example code and incorporate Mongo in a future rewrite of my latest vb/access project as a C# mongo combo.  What I'm most curious about this rewrite is how well will my end project lend itself to being a standalone desktop application.  Functionality, stability and ease of deployment are the areas of concern.  If deployment makes my life easier I'm already liking it.

    • Re: Go

      Posted by CBennett on 07/06/2010 09:59pm

      I did a little bit of looking around and I wasn't able to find anything specifically regarding embedding MongoDB within your application; however, MongoDB is self contained. It should be possible to deploy the required MongoDB files with your isntaller. Then to start it you could simply launch the MongoDB process when your application starts up. This should allow you embed MongoDB for your application and control the process. Let me know if you have any questions. Thanks Chris

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • By providing developers with the right tools to detect, understand, and fix problems early, your business can simplify software development, shorten development lifecycles, and improve the quality of software code. The end result is increased innovation, secure applications, and a faster time to market — all at a lower cost.

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date