Click here to Skip to main content
15,881,027 members
Articles / Web Development / ASP.NET

MONGO is as SWEET as a MANGO

Rate me:
Please Sign up or sign in to vote.
4.91/5 (42 votes)
10 Jun 2013CPOL15 min read 40.5K   789   66  
Developing .Net application with Mongo Db as Back end

 

Introduction:  

Image 1

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?<o:p>

 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.<o:p>

MONGO DB is a Leading NoSQL Data base.<o:p>

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.<o:p>
 

Few Things about Mongo: 

Before start using I would like to say few more things about MONGO.<o:p>

 

  • ·          Mongo is developed by 10gen.
  • ·         Mongo developed in C++.<o:p>  
  • ·         Mongo is a Document oriented Data base.<o:p>  
  • ·         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.<o:p> 

Remember these things, will be use full in future.<o:p> 
Installation: 

Are you ready for the installation … and use …
Actually speaking it’s not an installation it’s just Downloading…<o:p>
 

 

  • ·          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:<o:p> 

Download  zip file<o:p>

 

Go to the url http://www.mongodb.org/downloads
then you can see a screen as below.<o:p> 
Image 2

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.<o:p>

 

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.<o:p> 

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...
<o:p>

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 Image 3

 Finished! That’s all

What we have to do next..?<o:p> 

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 :
 

Image 4

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

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...?<o:p>

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

Let’s see what had happened.Image 6

 

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.<o:p>

 

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= " /> .
<o:p>
 Image 8

<o:p> 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.<o:p>

And I got a response as below.Image 9
<o:p> 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.exeImage 10
 <o:p>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. Image 11

Hope everything went well.
<o:p>
 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.<o:p>

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!!!!!! …   <o:p>

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…<o:p>


 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?<o:p>

Then to the command prompt issue the command mongo or mongo.exe again and see what happened.<o:p>

You will get a screen as below
 
Image 12

 

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.<o:p>

The basic command to insert is     

 

<span style="line-height: 115%;">***********************
BASIC INSERT COMMAND
***********************
db.test.save( { KodothTestField: ‘Myname is Kodoth’ } ) </span>

 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.Image 13
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() Image 14

 

 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.<o:p>

 

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?<o:p>

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.<o:p>

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…<o:p>

First I will show you how the data will look in a relational DB.<o:p>

For example consider an Employee table and a Student table in relational way. The schemas would be entirely different right? Yes exactly…
<o:p>
 Image 15

Let us now see how it will look in Mongo DB. The above two tables are combined into single Collection in Mongo…<o:p> 
Image 16

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.<o:p>

If you want to try out you can use below test scripts 
<o:p>

***********************
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?<o:p>

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.<o:p>

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

Image 17

Here am listing out the dlls which I got on unzipping the application to avoid confusion.<o:p>

 

  1. ·         MongoDB.Bson
  2. ·         MongoDB.Driver<o:p>  

 

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

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 .
Image 18

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.<o:p>
 

Image 19

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.<o:p> 
Image 20

 Next step is to create UI for our Application. Image 21

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

 

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.
<o:p>
 Image 22
 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? <o:p>

Like all other applications we have to establish a connection with our DB. <o:p>

I know that you might be thinking of web.config, ADO.Net ConnectionStrings blaha blaha blaha... right?
<o:p>

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

It is very simple right? <o:p>

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?<o:p>

 I think we have to code the save and close buttons now.<o:p>

 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.<o:p>
 

After instantiating the Employee, insert the Employee object to the DB using Mongo API methods.<o:p>

How can we do the insert?
Do mongo APIs having the capability?<o:p>

 


The code written for the click event answers the above questions:<o:p> 

C#
***********************
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 (). <o:p>

Yes, everything looks perfect; there is no data or record present in the collection.<o:p>

I am going to run the code to save a record in our Employe_Manager DB.Image 24
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 ….?


Image 25

 Hurrayyyyy …!!! The record got inserted in the DB successfully .he was true right…<o:p>

That’s it... Again Mongo told us He is as Sweet as a Mango.<o:p>

Very simple, did you felt that you have inserted in to a data base, or written in to a file.<o:p>

No, very much not! Mongo is simple, right?<o:p>

 

So we are successful in performing insert operation.
<o:p>

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 .<o:p>

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.

C#
***********************
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. <o:p>

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

Image 27

We have done our binding perfectly.<o:p>


What we are going to do next is Edit/Update operation on our application. <o:p>

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.
<o:p>
 Image 29
Click the Edit button to expand the Edit view:

 Image 30
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.

C#
***********************
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.

Image 31
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.<o:p> 

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. <o:p>

 

Now what you think is this Scalable? Shall we replace SQL with Mongo?<o:p> 


 

 


<o:p> 

 

 

 

License

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


Written By
Software Developer (Senior)
United States United States
Currently working as Application Development Consultant in USA
I love writing what i know about and learning from the mistakes which i make...

Comments and Discussions

 
-- There are no messages in this forum --