Click here to Skip to main content
Click here to Skip to main content

MONGO is as SWEET as a MANGO

, 10 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Developing .Net application with Mongo Db as Back end

Editorial Note

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction:  

This time I am trying to put in some idea about MONGO Db.
Any way I know that Mongo db is not a new thing for the developers , but we the .Net guys are not using this extensively in our development stuffs.  In the era of JSON and JavaScript Frameworks we are still walking with SQL server or Oracle without really thinking of size of the application.
Even if we require only a small DB, we will go for SQL Server or Oracle. Am I right? Well ….we will not even think about the relevance of a data base in our application. For small applications we require small DBs… Why do we need to going for Giants?

 In the past few lines I mentioned Small Database …. Small DB etc..  You might be thinking what I really meant by that … right?  If we want to define a small database, say size less than 2GB, without much relations with other tables (say require huge joins to get a meaning full data row ) or data which cannot be stored in a relational format (row and column format), we can go for DBs like MONGO.

MONGO DB is a Leading NoSQL Data base.

The name MONGO came from "huMONGOus" meaning "extremely large"

Here I am trying to explain the Mongo Db installation, and how to use it with our C# applications. While writing I tried to include the errors which I have encountered from my experience also. Because one day or other definitely you may come across those and by that time I don’t want you to search again to resolve those issues.
 

Few Things about Mongo: 

Before start using I would like to say few more things about MONGO.

  • ·          Mongo is developed by 10gen.
  • ·         Mongo developed in C++.  
  • ·         Mongo is a Document oriented Data base.  
  • ·         Mongo stores all Data in form of JSON.
  • ·         Mongo Receives Data in the form of JSON.
  • ·         For Mongo JSON is BSON(Binary JSON).
  •    Mongo is a structure less DB, i.e.,  it is not necessary that one row in a table must be in same schema like other (Schema Less).

That’s why it’s not “Table” but “Collection” in Mongo. 

Remember these things, will be use full in future. 
Installation: 

Are you ready for the installation … and use …
Actually speaking it’s not an installation it’s just Downloading…
 

  • ·          Download  zip file [http://www.mongodb.org/downloads]
  • ·         Extract it and just copy the files into a desired location in your machine.
  • ·         Start the DB engine.
  • ·         Test the installation and use it.

That’s it so simple, right? Ok let’s start: 

Download  zip file

Go to the url http://www.mongodb.org/downloads
then you can see a screen as below.
 

Am using a windows 7 32 bit machine that’s why I downloaded that package marked as red.

Click download don’t hesitate its matter of few seconds.

Wow..I got that down loaded it was a zipped file with name mongodb-win32-i386-2.4.4.zip.
The name of the folder will change according to the version you down load, here I got 2.4.4 version of mongo. OK all set.
Extract it and just copy the files into a desired location in your machine.

Extract the zipped file then copy the extracted file to your required drive in your BOX. 

Any way Am going to copy files in to my D drive, since I don’t have many files in my D:
 .. Alright then where are you planning to paste the mongo files in C: or in your Desk top it self..? Ok no matter where ever you paste...

In the below given snap shot you can see that I have navigated to the bin folder inside the Mongo File  and also I could count till fifteen files inside bin  and what about you 

 Finished! That’s all

What we have to do next..? 

Start the DB engine  

Let’s go and start using our mongo db...
Open up a command prompt then Navigate to bin in the D :
 



Type mongo.exe (which is the command used to start mongo Db Power shell)
then see the below response.. 

That was an awesome exception  J LOL …
What is that?
Couldn’t connect to the server .Why the exception happened any idea... Did I create any server in between..? No right then how come it connect to server...Silly Machine …
J
Yea I got it like all other DBs we have to start the DB engine before using it .
How can we start it...?

 We have to start mongo db by using the command mongod,from the same location i.e. the bin folder of mongo hit mongod.

Let’s see what had happened.

Again a wonderfully formatted exception J we got right? Did you notice d what I have highlighted on top? Yea it is the mongod command and the second one is the exception asking us to create folder s called data.
Inside the data again a folder called db.

So we have to create these data\db folders.
Next question is where we have to create these folders?
We have to create the folder by default in the C drive of our BOX in which we are installing our mongo. Let’s go and create the folder structure in C drive.
 
Again a question arises here is, is it mandatory to create the data\db directories inside C …? Nooo, not actually you can create where ever you want .but only thing is that you have to tell the MONGO that we have created the data folders in this particular location i.e. we have to set the db path for mongo.exe.
Ok here am creating in some other location not in c for better understanding of this option too. Am going to create the db folders in D drive root, with the help of command prompt.
 Why because it’s an opportunity for us to remember the old dos commands... Smile | <img src= " /> .
 

 The next step is to set the Db path to mongo.exe.

Again navigate back to bin enter the command mongod.exe --dbpath d:\data.

And I got a response as below.
 Hope everything went well... Because I didn’t see any ERROR *** in the console J

As a next step we can go and start the db using the command >start mongo.exe
 
Here also I didn't saw any error or warning message … the again we have to supply a command to make this running and up i.e. mongod will get a response in console as below. 

Hope everything went well.
 Test the Mongo DB installation

Now we have to see our DB right?
Yea very much, Otherwise how will we believe it’s Up and running.

For testing purpose MONGO has got a DB called test by default in it .lets goo and query that.
How? Do we have got any management studio..? Like SQL no we have to depend again command prompt for the same.
COMMAND PROMPT!!!!!! …  

Yes exactly the same command prompt… our good old command prompt…
Heiiiii..  Don’t get afraid yes it’s our old command prompt only.
Ok let’s go and see how we are going to use it…


 Ohhh Nooo… don’t close the above Command prompt leave it as it is…
Let’s go and open a new one kk.
Navigate to Bin as usual we do…
I am sure you people may be remembering the old C programming which we have done on our college day’s right
J?

Then to the command prompt issue the command mongo or mongo.exe again and see what happened.

You will get a screen as below
 

As a next step .I mentioned before that Mongo has got a test db by default called test, try inserting one record in to it.
The next question here is how will we insert? Does mongo has got SQL query? Exactly not mongo has got only commands to help with.

The basic command to insert is     
***********************
BASIC INSERT COMMAND
***********************
db.test.save( { KodothTestField: ‘Myname is Kodoth’ } ) 
 Where test is the DB and .save is the command to insert and KodothTestField is the column or Field name and My name is Kodoth is the value.
Our Data got successfully inserted … Hurrayyyyyy..
Before talking more let’s check whether it’s stored or not by supplying another command.
db.test.find() 

 Yes it’s there …
I know that you are thinking about the number which is displayed with every record right called ObjectId .It’s like the Identity field in SQL which we do auto increment and all, have a close look you can see that the Object Id ends with 92, so it’s different for each and every record.

At last we are successful in installing and verifying the MONGO right. Let’s have a party...
So do you agree now MONGO is as Sweet as MANGO?

Also we have got 3rd party tools to explore the MONGO db called MONGO VUE. Using this tool we can perform operation against the mongo DB like we use Management studio for SQL Server.

Can you just imagine that our SQL server or Oracle Db with entirely different row in same table? Is it possible in our relational DB table? Here in mongo it happens. I will show you how we can do that…

First I will show you how the data will look in a relational DB.

For example consider an Employee table and a Student table in relational way. The schemas would be entirely different right? Yes exactly…
 

Let us now see how it will look in Mongo DB. The above two tables are combined into single Collection in Mongo… 

This is how Collections are stored in Mongo. I think now you can feel the difference really right?
Every thing came under a single umbrella. This is not the right way but I just wanted to show you all how this happens that’s why I combined 2 entirely different tables in to one single Collection.

If you want to try out you can use below test scripts 

***********************
TEST INSERT SCRIPTS
*********EMPLOYEE******
db.test.save( { EmployeId: "1", EmployeFirstName: "Kodoth",EmployeLastName:"Kodoth Last",EmployeAge:"14" } ) 
db.test.save( { EmployeId: "2", EmployeFirstName: "Kodoth 2",EmployeLastName:"Kodoth Last 2",EmployeAge:"14" } ) 
db.test.save( { EmployeId: "3", EmployeFirstName: "Kodoth 3",EmployeLastName:"Kodoth Last 3",EmployeAge:"14" } ) 
******STUDENT******
db.test.save( { StudentId: "1", StudentName: "StudentName",StudentMark:"25" } ) 
db.test.save( { StudentId: "2", StudentName: "StudentName 2",StudentMark:"26" } ) 
db.test.save( { StudentId: "3", StudentName: "StudentName 3",StudentMark:"27"} )
************************

 To operate on Mongo you can refer http://docs.mongodb.org/manual/reference/method/
mongo shell methods.

From where we get drivers for Mongo to use in C#: 

We need a driver to connect application / language to a DB. As a developer what we want is the driver for the Mongo DB, is it?

You can use the given link to download the driver for our c# application
https://s3.amazonaws.com/drivers.mongodb.org/dotnet/CSharpDriver-1.8.1.zip.
We will get a zipped file called CSharpDriver-[version].
Let’s see what’s inside that file and how we are going to use it.

I could see around 9 files inside including text and pdb files and how about you, is that count nine itself or more...? 


Here am listing out the dlls which I got on unzipping the application to avoid confusion.

  1. ·         MongoDB.Bson
  2. ·         MongoDB.Driver  

Both the dlls are very small in size less than 412 Kb .so don’t think that is heavy. 

Star Castings Relational vs Mongo
Before we dive in to mongo I just wanted you to know what is what in Relational Db and in mongo .See below comparison, actually it’s not a comparison buts as I mentioned a casting .

Our First Mongo C# Application:
Actually my intention is to create a small Employee Add, Edit and View application.
It would be having an 

  • Employee Add Page, 
  • Employee Edit Page and 
  • View Page 
OK is this enough for you people to go and use Mongo as your DB? JLets Go and open up our visual web developer..

I Used visual web developer 2010 edition for this example.
Let’s start creating a web project with name MangoMONGO.
As the next step I would like to add the 2 ddl's which we have unzipped before in to our application by adding reference.
 

Ok our Visual studio is ready .then what we want?
 Yea the Data Base to Store the Data.
Let’s Create a DB with name EMPLOYE_MANAGER in our local Mongo the Mango
J
How...? I only told you to do insert and select operations that also we did with our default test database provided by default. Lets go and create a Mongo DB Quick

***********************
CREATING MONGO DB
***********************
> use EMPLOYE_MANAGER  //Creates a db with the provided name
switched to db EMPLOYE_MANAGER
> db.users.save({username:"kodoth"})//Saves the created DB ,with out saving will not get created
> show dbs //Displays all the Db in the server
EMPLOYE_MANAGER 0.0625GB
local   0.03125GB
test    0.0625GB <span style="color: rgb(17, 17, 17); font-size: 14px; font-family: 'Segoe UI', sans-serif;">You can
see below how it looked when I typed “show dbs” after creating our Employe_Manager
DB.<o:p /></span><span style="color: rgb(17, 17, 17); font-family: 'Segoe UI', Arial, sans-serif; font-size: 14px;"> </span>

You can see below how it looked when I typed “show dbs” after creating our Employe_Manager DB. 

 Next step is to create UI for our Application. 

We are done with our UI. Now you can go and start coding to take the data from UI to our Mango the DB.

Inserting Name, Department, Age and Salary is not a big deal while considering the SQL. To insert using SQL first we will go and create a stored procedure, then lots of other process and procedures right? In mongo what we do is will create an Entity class for Employee then bind the entity with the required data from UI . Then insert to the DB, that’s all finished. Lets watch how it can be done, in practical.
First I’ll be creating an Entity Class called Employee like all our applications.
 
 You have noticed that Id is of type MongoDB.Bson.ObjectId , and it is the primary key now.

Everything is set then what would be our next step?

Like all other applications we have to establish a connection with our DB.

I know that you might be thinking of web.config, ADO.Net ConnectionStrings blaha blaha blaha... right?

Don’t think that much… It’s very simple… I’ll show you how to establish a connection with 2 lines of code. 

It is very simple right?

One thing you have to make note while establishing connection is check whether the Mongo server is up and running in your Machine.
Then what we have to do next?

 I think we have to code the save and close buttons now.

 In save Button: 

Instantiate Employee Object.
Assign value to properties from text box expect to the ObjectId field, which is the primary key field with an auto increment identity in Mongo.
 

After instantiating the Employee, insert the Employee object to the DB using Mongo API methods.

How can we do the insert?
Do mongo APIs having the capability?


The code written for the click event answers the above questions:
 

***********************
SAVE BUTTON CODE SNIPPET
***********************
protected void btnSave_Click(object sender, EventArgs e)
        {
            ///Establish Connection
            MongoDatabase mdb = GetConnectedToMongo();
            ///Get The Collection in which you have to insert the record
            var collection = mdb.GetCollection<Employee>("Employee");
            ///Fill the Employee Entity
            Employee objEmp = new Employee();
            objEmp.Name = txtName.Text;
            objEmp.Salary = txtSalary.Text;
            objEmp.Department = txtDepartment.Text;
            objEmp.Age = Convert.ToInt32(txtAge.Text.Trim());
            ///Finally Insert
            collection.Insert(objEmp);
            ///Get the id of inserted record in return
            var id = objEmp.Id;
            if (id.ToString() != "")
            {
                lblResponse.Visible = true;
                lblResponse.Text = lblResponse.Text + id.ToString();
            }
        }

I think we have to try executing the code.
Before that I just want to remind you that in Mongo we call table as Collection.
Here we are going to insert data in Collection Employee in “EMPLOYE_MANAGER” db.
Before that lets make sure that there is no data in Employee Collection by the help of Shell command > db.Employee.find ().

Yes, everything looks perfect; there is no data or record present in the collection.

I am going to run the code to save a record in our Employe_Manager DB.
Our Code executed successfully and we got an Employee Id for William, saying that this particular record is inserted in the DB. Are you sure?
I think we have to check directly in DB that whether the record is inserted, or he is simply lying.
I went and executed our Find command in Db Command prompt ,
then do you want to see what result I got ….?

 Hurrayyyyy …!!! The record got inserted in the DB successfully .he was true right…

That’s it... Again Mongo told us He is as Sweet as a Mango.

Very simple, did you felt that you have inserted in to a data base, or written in to a file.

No, very much not! Mongo is simple, right?

So we are successful in performing insert operation.

List Employees 
Now, we have to see how we retrieve the records and display in our UI.
I am planning this process in another page. Since we are using Default template of Development express we have got 2 pages, Default.aspx and About.aspx. We have used the Default page to do the insert operation and now we are going to use the About.aspx page.
And I created another class file called MONGOConnect.cs to write the DB connections, like a DB Helper for SQL .

I am going to List all the employees in the Employee Collection in an ASP grid.

Get the records from collection, and then create a data source with those records, after that set it as the data source of that ASP grid, and bind it.

***********************
BINDING TO GRID VIEW
***********************
protected void Page_Load(object sender, EventArgs e)
        {
            MONGOConnect objMC = new MONGOConnect();//Helper Class
            var collectionEmployee = objMC.GetMongoCollection("Employee");//Gets Employee Collection
            var lstEmployee = collectionEmployee.AsQueryable<Employee>().ToList<Employee>(); //Queries the Employee collection and Converts to List            
            grdListEmployee.DataSource = lstEmployee;//Set the List as Data source  
            grdListEmployee.DataBind();//Binds the Grid
        }

Hope you have understood the above mentioned steps from the Page_Load code.

See the below data bound grid…
So beautiful right?  Smile | <img src= " />

We have done our binding perfectly.


What we are going to do next is Edit/Update operation on our application.

For this I thought we have to go for our old Grid View’s Edit functionality withTemplate columns. Take this as an opportunity to brush-up you Grid View knowledge  Smile | <img src= " />
I have added one more Column to place Edit button in the Grid view.
 
Click the Edit button to expand the Edit view:

 
To make this functionality I have added a few lines of code under respective Events.

The main functionality falls under On Row Update Event handler of the Grid View.

***********************
ROW UPDATING
***********************
protected void grdListEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var empId = grdListEmployee.DataKeys[e.RowIndex].Values["Id"].ToString(); 
          
            TextBox txtName = (TextBox)grdListEmployee.Rows[e.RowIndex].FindControl("txtName");
            TextBox txtDepartment = (TextBox)grdListEmployee.Rows[e.RowIndex].FindControl("txtDepartment");
            TextBox txtAge = (TextBox)grdListEmployee.Rows[e.RowIndex].FindControl("txtAge");
            TextBox txtSalary = (TextBox)grdListEmployee.Rows[e.RowIndex].FindControl("txtSalary");
            Employee objEmp = new Employee();
            objEmp.Id = ObjectId.Parse(empId);
            objEmp.Name = txtName.Text;
            objEmp.Salary = txtSalary.Text;
            objEmp.Age =Convert.ToInt32(txtAge.Text);
            objEmp.Department = txtDepartment.Text;
            MONGOConnect objMC = new MONGOConnect();//Helper Class
            var collectionEmployee = objMC.GetMongoCollection("Employee");//Gets Employee Collection
            collectionEmployee.Save(objEmp);//Updates the Db with the empId
            grdListEmployee.EditIndex = -1;
            BindGridView();
        } 

I have updated record with name Raj. Let’s see what happened to Raj.


So we could successfully able to perform all the Insert, List, and Update operation.

This would be enough for Beginners in Mongo to get started. 

You Can Down Load Source Code Here Download MangoMONGO-noexe.zip     

Conclusion: 

At last I was able to finish, I thought I’ll never… because, I got an inspiration to write more and more as I went deep into the features of Mongo, and the support that the .Net APIs provide. Initially I thought that this DB might be helpful only for Java, but now I came to a conclusion that it’s very much supportive for .Net developers than Java. The APIs are beautifully developed with support to LINQ.

Now what you think is this Scalable? Shall we replace SQL with Mongo? 


 


 

 

License

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

Share

About the Author

K K Kodoth
Software Developer (Senior)
United States United States
Currently working as Systems Analyst in a Leading MNC in India,
I love writing what i know about and learning from the mistakes which i make...

Comments and Discussions

 
QuestionRetrieve Refrences Collections PinmemberMahdi K.18-Nov-14 15:41 
GeneralMy vote of 4 Pinmembervinayraghavendra.hs6-Feb-14 23:38 
QuestionNice article Pinmemberjtpatil29-Jul-13 12:37 
AnswerRe: Nice article PinmemberK K Kodoth29-Jul-13 19:45 
AnswerRe: Nice article PinmemberGregoryW10-Sep-13 2:36 
QuestionSuperb article PinmemberMember 1012240223-Jun-13 7:52 
GeneralAs for your "replace SQL with mongo" PinmemberObiWan_MCC17-Jun-13 1:12 
GeneralAs for your "replace SQL with mongo" PinmemberObiWan_MCC17-Jun-13 1:11 
GeneralNice article [modified] Pinmemberjohn-ph10-Jun-13 20:54 
AnswerRe: Nice article PinprofessionalK K Kodoth10-Jun-13 21:06 
GeneralRe: Nice article Pinmemberjohn-ph10-Jun-13 21:21 
AnswerCan't see images PinmemberClifford Nelson10-Jun-13 6:47 
GeneralRe: Can't see images PinprofessionalK K Kodoth10-Jun-13 19:30 
AnswerRe: Can't see images PinmemberClifford Nelson11-Jun-13 5:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141223.1 | Last Updated 11 Jun 2013
Article Copyright 2013 by K K Kodoth
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid