Click here to Skip to main content
15,867,453 members
Articles / Database Development / MongoDB
Article

Getting started with MongoDB

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL3 min read 8K   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.

    <span style="color:blue;">using</span> System;
    <span style="color:blue;">using</span> System.Xml.Linq;
    <span style="color:blue;">using</span> MongoDB.Bson;
    <span style="color:blue;">using</span> MongoDB.Driver;<br />
    <br /><br /><br /><br /><span style="color:blue;">namespace</span> WikiExampleConsole
    {
    <span style="color:blue;"> class</span> <span style="color:#2b91af;">Program</span>
        {
    <span style="color:blue;"> static</span> <span style="color:blue;">void</span> Main(<span style="color:blue;">string</span>[] args)
            { 
    	   <span style="color:#2b91af;">MongoServer</span> mongo = <span style="color:#2b91af;">MongoServer</span>.Create();
    	   mongo.Connect();
     
    	   <span style="color:blue;">var</span> db = mongo.GetDatabase(<span style="color:#a31515;">"tutorial"</span>);
     
    	   ...		
     
    	   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.

    <span style="color:blue;">...<br />using</span> (mongo.RequestStart(db))
    {<br /><span style="color:blue;"> var</span> collection = db.GetCollection<<span style="color:#2b91af;">BsonDocument</span>>(<span style="color:#a31515;">"books"</span>);<br />    ...
    }<br /><br />...

    Store data

    <span style="color:blue;">using</span> (mongo.RequestStart(db))<br />{
    <span style="color:blue;"> var</span> collection = db.GetCollection<<span style="color:#2b91af;">BsonDocument</span>>(<span style="color:#a31515;">"books"</span>);<br /> 
    <span style="color:#2b91af;"> BsonDocument</span> book = <span style="color:blue;">new</span> <span style="color:#2b91af;">BsonDocument</span>()
            .Add(<span style="color:#a31515;">"_id"</span>, <span style="color:#2b91af;">BsonValue</span>.Create(<span style="color:#2b91af;">BsonType</span>.ObjectId))
            .Add(<span style="color:#a31515;">"author"</span>, <span style="color:#a31515;">"Ernest Hemingway"</span>)
            .Add(<span style="color:#a31515;">"title"</span>, <span style="color:#a31515;">"For Whom the Bell Tolls"</span>);
     
        collection.Insert(book);<br />}

    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.

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

    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?

    <span style="color:blue;">...<br />foreach</span> (<span style="color:#2b91af;">BsonElement</span> element <span style="color:blue;">in</span> item.Elements)
    {
    <span style="color:#2b91af;"> Console</span>.WriteLine(<span style="color:#a31515;">"Name: {0}, Value: {1}"</span>, element.Name, element.Value);
    }<br /><br />...

    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

    <span style="color:blue;">using</span> System;
    <span style="color:blue;">using</span> System.Xml.Linq;
    <span style="color:blue;">using</span> MongoDB.Bson;
    <span style="color:blue;">using</span> MongoDB.Driver;<br />
    <span style="color:blue;">namespace</span> WikiExampleConsole
    {
    <span style="color:blue;"> class</span> <span style="color:#2b91af;">Program</span>
        {
    <span style="color:blue;"> static</span> <span style="color:blue;">void</span> Main(<span style="color:blue;">string</span>[] args)
            {
    	   <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"Connect..."</span>);
     
    	   <span style="color:#2b91af;">MongoServer</span> mongo = <span style="color:#2b91af;">MongoServer</span>.Create();
    	   mongo.Connect();
     
    	   <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"Connected"</span>);<br />            <span style="color:#2b91af;">Console</span>.WriteLine();
     
    	   <span style="color:blue;">var</span> db = mongo.GetDatabase(<span style="color:#a31515;">"tutorial"</span>);
     
    	   <span style="color:blue;">using</span> (mongo.RequestStart(db))
    	   {
    	       <span style="color:blue;">var</span> collection = db.GetCollection<<span style="color:#2b91af;">BsonDocument</span>>(<span style="color:#a31515;">"books"</span>);
     
    	       <span style="color:#2b91af;">BsonDocument</span> book = <span style="color:blue;">new</span> <span style="color:#2b91af;">BsonDocument</span>()
    	           .Add(<span style="color:#a31515;">"_id"</span>, <span style="color:#2b91af;">BsonValue</span>.Create(<span style="color:#2b91af;">BsonType</span>.ObjectId))
    		  .Add(<span style="color:#a31515;">"author"</span>, <span style="color:#a31515;">"Ernest Hemingway"</span>)
    		  .Add(<span style="color:#a31515;">"title"</span>, <span style="color:#a31515;">"For Whom the Bell Tolls"</span>);
     
    	       collection.Insert(book);
     
    	       <span style="color:blue;">var</span> query = <span style="color:blue;">new</span> <span style="color:#2b91af;">QueryDocument</span>(<span style="color:#a31515;">"author"</span>, <span style="color:#a31515;">"Ernest Hemingway"</span>);
     
    	       <span style="color:blue;">foreach</span> (<span style="color:#2b91af;">BsonDocument</span> item <span style="color:blue;">in</span> collection.Find(query))
    	       { 
    		  <span style="color:#2b91af;">BsonElement</span> author = item.GetElement(<span style="color:#a31515;">"author"</span>);
    		  <span style="color:#2b91af;">BsonElement</span> title = item.GetElement(<span style="color:#a31515;">"title"</span>); <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />		  <br />                    <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"Author: {0}, Title: {1}"</span>, author.Value, title.Value);
     
    		  <span style="color:blue;">foreach</span> (<span style="color:#2b91af;">BsonElement</span> element <span style="color:blue;">in</span> item.Elements)
    		  {
    		      <span style="color:#2b91af;">Console</span>.WriteLine(<span style="color:#a31515;">"Name: {0}, Value: {1}"</span>, element.Name, element.Value);
    		  }
     	       }<br />            }
     
    	   <span style="color:#2b91af;">Console</span>.WriteLine();
                <span style="color:#2b91af;">Console</span>.Read();
     
    	   mongo.Disconnect();
    	}<br />    }
    }

    Download

    The sample solution can be downloaded from the MSDN samples.

    Further reading

    License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


    Written By
    United States United States
    The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

    The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
    This is a Collaborative Group

    755 members

    Comments and Discussions

     
    -- There are no messages in this forum --