Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Getting started with MongoDB

0.00/5 (No votes)
20 Jan 2012 1  
Getting started with MongoDBMongoDB is a famous representative of NoSQL databases. It is a document-oriented database, which means that data will

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

Getting started with MongoDB

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 favourite 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

    using System;
    using System.Xml.Linq;
    using MongoDB.Bson;
    using MongoDB.Driver;
    namespace WikiExampleConsole { class Program { static void Main(string[] args) { Console.WriteLine("Connect..."); MongoServer mongo = MongoServer.Create(); mongo.Connect(); Console.WriteLine("Connected");
    Console.WriteLine(); var db = mongo.GetDatabase("tutorial"); 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); foreach (BsonElement element in item.Elements) { Console.WriteLine("Name: {0}, Value: {1}", element.Name, element.Value); } }
    } Console.WriteLine(); Console.Read(); mongo.Disconnect(); }
    } }

    Download

    The sample solution can be downloaded from the MSDN samples.

    Further reading

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here