MongoDB is a famous representative of NoSQL databases. It is a document-oriented database, which means that data will be stored in documents. In this article, we will see how to set up MongoDB for Windows and how you can get started with it.

Setting up MongoDB for Windows

First, download the MongoDB binaries from the following site - http://www.mongodb.org/downloads and unzip the downloaded binaries to a folder of your choice. Now you have to create a folder where MongoDB can store the data. This won't be created automatically.

Execute the following command in your shell:

C:\> mkdir \data
C:\> mkdir \data\db

At the last step, lets run MongoDB. Navigate to your MongoDB folder and execute the mongod.exe:

C:\> cd \my_mongo_dir\bin
C:\my_mongo_dir\bin>mongod

Now we are ready to start. If you want to open the shell admin console, use the following command:

C:\my_mongo_dir\bin>mongo

You can also use the web-based admin console - http://localhost:28017/

A detailed guide can be find on the following site - http://www.mongodb.org/display/DOCS/Quickstart+Windows

Working with MongoDB

Setting up our database

For this example, we will work on a database, which stores authors and their books. To reduce complexity we use a simple console application, but you can use everything learned also in ASP.NET. Let us set up our database and our collection.
If you now not have, start the mongo.exe from the shell:

C:\my_mongo_dir\bin>mongo

To get familiar with the commands you can use, type in the following:

> help

You will see a list with the server-wide commands. For now, we will just create a new database:

> use tutorial

If the database exists you will be connected to it. If not, a new database will be created.
To see more database-specific command use the following command:

> db.help()

The last step in setting up our database is to create a collection:

> db.createCollection(books)

Now we are ready to start coding.

File - New - Project

Create a new Console Application and name it whatever you want. You can use different APIs for working with MongoDB. My favorite is the official C# Driver, which you can get via NuGet - http://www.nuget.org/List/Packages/mongocsharpdriver

Connect to MongoDB

First we will connect to our earlier created database.

using System;
using System.Xml.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
 
namespace WikiExampleConsole
    class Program
    
        static void Main(string[] args)
        {
            MongoServer mongo = MongoServer.Create();
            mongo.Connect();
            var db = mongo.GetDatabase("tutorial");
            ...
            mongo.Disconnect();
        }
    }
}

This code is mostly self-explanatory. First you create a MongoServer object and connect to our tutorial database.
After all, don't forget to close the connection.

Get a collection

As the second step, we will connect to our book collection.

 
...
using (mongo.RequestStart(db))
{
    var collection = db.GetCollection<BsonDocument>("books");
    ...
}
...

Store data

using (mongo.RequestStart(db))
    var collection = db.GetCollection<BsonDocument>("books"); 
    BsonDocument book = new BsonDocument()
        .Add("_id", BsonValue.Create(BsonType.ObjectId))
        .Add("author", "Ernest Hemingway")
        .Add("title", "For Whom the Bell Tolls");
    collection.Insert(book);
}

Here we create a new instance of a BsonDocument and add an id, the name of the author and the title of the book. After all we only have to insert the document into the collection. Our document will now look something like this:

{ "_id" : 7, "author" : "Ernest Hemingway", "title" : "For Whom the Bell Tolls" }

Query data

We now have our data in position and it's time to get some results from our database. For now we just want the name of the author and the title of the book.

...
using (mongo.RequestStart(db))
    var collection = db.GetCollection<BsonDocument>("books"); 
    BsonDocument book = new BsonDocument()
        .Add("_id", BsonValue.Create(BsonType.ObjectId))
        .Add("author", "Ernest Hemingway")
        .Add("title", "For Whom the Bell Tolls");
    collection.Insert(book); 
     
    var query = new QueryDocument("author", "Ernest Hemingway"); 
 
    foreach (BsonDocument item in collection.Find(query))
    
        BsonElement author = item.GetElement("author");
        BsonElement title = item.GetElement("title"); 
 
        Console.WriteLine("Author: {0}, Title: {1}", author.Value, title.Value);
    }
    ...
}
...

First we define our query. It's like a key-value-query. What a surprise, we search for Ernest Hemingway.
The Find-method executes our query and with the BsonDocument instance we can grab our author and the book title.

So, now we have our specific data. But what to do if we need all the data?

...
foreach (BsonElement element in item.Elements)
    Console.WriteLine("Name: {0}, Value: {1}", element.Name, element.Value);
}
...

Now we're finished. I hope you had a bit of fun and also learned a little bit. Below you can find the complete code

The complete code

01.using System;
02.using System.Xml.Linq;
03.using MongoDB.Bson;
04.using MongoDB.Driver;
05. 
06.namespace WikiExampleConsole
07.
08.    class Program
09.    
10.        static void Main(string[] args)
11.        {
12.            Console.WriteLine("Connect...");
13. 
14.            MongoServer mongo = MongoServer.Create();
15.            mongo.Connect();
16. 
17.            Console.WriteLine("Connected");
18.            Console.WriteLine();
19. 
20.            var db = mongo.GetDatabase("tutorial");
21. 
22.            using (mongo.RequestStart(db))
23.            {
24.                var collection = db.GetCollection<BsonDocument>("books");
25.                BsonDocument book = new BsonDocument()
26.                    .Add("_id", BsonValue.Create(BsonType.ObjectId))
27.                    .Add("author", "Ernest Hemingway")
28.                    .Add("title", "For Whom the Bell Tolls");
29.                collection.Insert(book);
30. 
31.                var query = new QueryDocument("author", "Ernest Hemingway");
32. 
33.                foreach (BsonDocument item in collection.Find(query))
34.                {
35.                    BsonElement author = item.GetElement("author");
36.                    BsonElement title = item.GetElement("title");  
37. 
38.                    Console.WriteLine("Author: {0}, Title: {1}",
39.                        author.Value, title.Value);
40. 
41.                    foreach (BsonElement element in item.Elements)
42.                    {
43.                        Console.WriteLine("Name: {0}, Value: {1}",
44.                            element.Name, element.Value);
45.                    }
46.                }
47.            }
48. 
49.            Console.WriteLine();
50.            Console.Read();
51. 
52.            mongo.Disconnect();
53.        }
54.    }
55.}

You can download the complete sample solution from here.

Further reading


See Also


Other Languages

This article is also available in the following languages:

Deutsch (de-DE)