Channels ▼
RSS

Database

MongoDB with C#


In my previous article, "Getting Started with MongoDB," I provided a brief overview about some of the most important things to consider when making the move from relational databases to the NoSQL world of MongoDB. I provided a sample conversion of a relational database schema to a document-oriented schema, suitable for MongoDB. In this second article in the three-part series, I develop an application that uses a C# driver to interact with a MongoDB database.

Learning Shell Commands with a GUI Tool

It is important to learn the different shell commands for MongoDB because the C# driver provides methods that mimic these commands and require similar parameters. MongoVUE is a GUI interface for interaction with MongoDB on Windows. (It comes in free and paid editions.) The free edition has limitations related to certain data import and MongoDB management features, but is suitable for most developer needs. It permits you to connect to a maximum of two servers and limits the number of maximum MDI views to three. Because the MongoDB shell is too error-prone for developers who are used to GUI tools, MongoVUE is a good alternative and it uses the MongoDB C# driver. You can download the latest version from the site. One nifty MongoVUE feature is that each time you perform an operation, the tool displays the specific command that you would require in the MongoDB shell in the Learn Shell panel. This way, you can learn the shell commands while you perform operations using the GUI tool.

The first time you execute MongoVUE, you need to setup the connection to your MongoDB database. Just click on the "+" button to open the Create New Connection dialog box, enter the desired name to identify the connection in MongoVUE, the server name, and the port (see Figure 1). Click Test to make sure that the parameters are OK, then click Save. Obviously, if you configured authentication in MongoDB, you will have to enter the username and password.

MongoDB connection in MongoVUE
Figure 1: Setting up a new MongoDB connection in MongoVUE.

Next, select the recently saved connection configuration and expand the retrogames database in the Database Explorer panel. You will be able to explore the indexes for both the games and the players collections (see Figure 2).

indexes
Figure 2: The indexes for the games and the players collection.

Double-click on the players collection and MongoVUE will retrieve the first 100 documents from the collection. You will be able to expand the key-value pairs shown in the default Tree View. The row inserted in the players collection displays the two embedded documents in the scores array (see Figure 3). Notice that the Learn Shell panel displays the MongoDB command executed to retrieve the first 100 documents: db.players.find().limit(100);.

shell command displayed in the Learn Shell panel
Figure 3: One document from the players collection shown in the Tree View and the shell command displayed in the Learn Shell panel.

Click on the Table View tab and you will see the same document in a grid that is very similar to the columns and rows used to display data retrieved from relational databases. If you hover the mouse pointer over the cell that displays Array[2], a tooltip will display the contents of the array (see Figure 4).

MongoVUE displaying the Table View
Figure 4: MongoVUE displaying the Table View for the players collection with the tooltip that shows the contents of an array.

Click on the Text View tab and you will see the JSON text of all the retrieved documents (see Figure 5).

MongoVUE displaying the JSON text
Figure 5. MongoVUE displaying the JSON text of all the retrieved documents from the players collection.

Now, follow the next steps to perform the same update "Getting Started with MongoDB" with the MongoDB shell, but this time using MongoVUE and some additional options:

  • Enter the following code in the Enter Find Json textbox (the first parameter for the update command):
{ name: "PUZZLEGAMESMASTER" }
  • Enter the following code in the Enter Update Json textbox (the second parameter for the update command):
{ $push: { scores: { game_id: new ObjectId("513a90ec507f318c7d15c744"),
                        game_name: "Invaders 2013",
                        score: 87925,
                        score_date: new Date(2013, 3, 3)
                     }
           }
  }
  • Click on the Count button that appears below the Enter Find Json textbox. A dialog box will indicate that the result of the following shell count command is 1:
db.players.find({ "name" : "PUZZLEGAMESMASTER" }).count();
  • Make sure that the Safe Mode checkbox is activated. You will find this checkbox below the Enter Update Json textbox.
  • Select the Updated Documents (using Find) radio button. You will find this radio button below the Enter Find Json textbox, at the right-hand side of the Last Error radio button. There are some problems with viewing all the controls that represent the checkboxes and radio buttons in some Windows versions.
  • Click the Update… button below the Enter Update Json textbox. MongoVUE will add a new document to the scores array to the document that matches the specified search criteria (see Figure 6).

MongoVUE displays the updated document
Figure 6: MongoVUE displays the updated document with a new element in the scores array, as a result of a successful safe update operation.

The Learn Shell log generates the following JavaScript:

  db.players.update(
      { "name" : "PUZZLEGAMESMASTER", "$atomic" : "true" },
      { $push: 
          { scores: 
              { game_id: new ObjectId("513a90ec507f318c7d15c744"),
                game_name: "Invaders 2013",
                score: 87925,
                score_date: new Date(2013, 3, 3)
              }
          }
      }
  , false, true);

Adding Indexes to Collections

MongoVUE is really useful for exploring the indexes of an existing collection. It's also helpful when you need to create new indexes. Follow these steps to create an index:

  • Right-click on the games collection in the Database Explorer panel and select Add Index… in the context menu. The New Index dialog box will appear.
  • Enter name for the index name. Because you already have a collection with data, you can take advantage of the visual index builder. Click on the Visual tab and a table with the available fields will appear. Click on the row for name and select Ascending (1) from the dropdown menu (see Figure 7).

Creating a unique index with MongoVUE
Figure 7: Creating a unique index with MongoVUE.

  • Activate the Unique checkbox in order to avoid future duplicates for this game's name.
  • Click on Create. MongoVUE will execute the command that creates the index and the following line will appear in the Learn Shell log:
db.games.ensureIndex({ "name" : 1 },{ "name" : "name", "unique" : true });
  • After MongoDB creates the index, MongoVUE will not automatically refresh the indexes list for the games collection in the Database Explorer panel. Thus, it is necessary to select the collection and click the Refresh button. After this step, you will see the new name index listed, and you will be able to check its properties (see Figure 8).

The new name index with its properties in MongoVUE
Figure 8: The new name index with its properties.

In this example, it isn't necessary to create the index in the background because there is just one document for the games collection. However, this won't be the case when you have existing collections with huge amounts of data. Obviously, adding indexes to collections with huge amounts of data in production environments is a resource-expensive operation and should be performed by experienced administrators.

Working with the .NET MongoDB C# Driver

The company behind MongoDB (10Gen) supports an official .NET driver, known as the MongoDB C# driver. This driver is written in C#, but it isn't limited to C#: You can also use it from other .NET languages such as Visual Basic and F#. You can download the latest version as either an MSI Windows installer file or as a zip file with the DLLs from GitHub. At the time of writing, the latest version of the driver was 1.7.0.4714 and its MSI Windows installer file name was CSharpDriver-1.7.0.4714.msi.

If you download the MSI Windows installer, the default location for the MongoDB C# driver DLLs will be C:\Program Files (x86)\MongoDB\CSharpDriver 1.7 for 64-bit Windows versions. If you download the zip file, you can unzip its contents in any desired folder. The MongoDB C# driver has two DLLs:

  • MongoDB.Bson.dll: The BSON library. It includes classes that represent the basic BSON types and the necessary classes for reading, writing, and managing BSON data. The classes include the required algorithms used in the serialization and deserialization of BSON data.
  • MongoDB.Driver.dll: The classes required to connect, interact, and execute commands on MongoDB databases.

Whenever you want to interact with a MongoDB database through the C# driver, the first step is to add a reference to the two previously mentioned DLLs in your project. I'll start with a very simple example of a Windows console application that just retrieves and displays some data from one of the previously created collections in the retrogames database. This way, you will see the basic namespaces, classes, types, and methods. The goal of the following Windows console application is to explore some of the options that you have when using the C# driver to interact with a MongoDB database.

To start with, create a new C# Windows console application in Visual Studio 2012 or 2010. You can target .NET Framework 4.5 or 4.0 according to the Visual Studio version you are using — I won't be using any specific .NET Framework 4.5 feature. Use RetrogamesConsole as the solution's name.

Once Visual Studio creates the new solution, add a new reference to the RetrogamesConsole project. In the Reference Manager dialog box, select Browse, then click on the Browse… button in order to locate and select the two DLLs required for the MongoDB C# driver in the Reference Manager: MongoDB.Bson.dll and MongoDB.Driver.dll (see Figure 9). Then click OK and you'll be ready to start adding the necessary code to interact with the MongoDB database.

Adding the necessary references to the project for the MongoDB C# driver
Figure 9: Adding the necessary references to the project.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video