Introduction To NO SQL And Working With MongoDB - Part One

We have seen many Applications use Relational Database Management System (RDBMS) like SQL Server, Oracle, MYSQL etc. as data repositories to applications. Almost all the relational databases support: 

  • Huge data storage
  • Support transactions (ACID)
  • Provide SQL to communicate to data
  • Vertical Scalability
  • Security
  • Fragmentation, replication , clustering etc

There are some problems in RDBMS, which many systems have experienced.

  • Relational Databases need a schema; we cannot add records to a database which have not been defined in the schema earlier.
  • We can’t add a record which does not fit the schema; for example, we cannot insert an integer data type to a DateTime data type in SQL Server.
  • We cannot add multiple items into a field.
  • We need to add nulls to unused columns in a row, which gives a performance hit.
  • Expensive regarding product cost, hardware, and maintenance; and there are a lot of problems with speed and availability
  • The overhead of writing complex SQL queries.

To avoid all these problems, the industry has come up/is coming up with the concept of NO SQL, which has the features given below:. 

  • No Overhead of transactions.
  • No complex SQL queries.
  • No burden of upfront schema design.
  • Provides easy and frequent changes to DB.
  • Fast development.
  • Performance improvement.
  • No single point of failure.

To accomplish all these features, some of the  industry leaders have come up with a new NO SQL database, and some of the leading NO SQL database providers are Cassandra, Couchbase, Amazon DynamoDB, MongoDB, Oracle No SQL Database, Clustrix, memSQL etc. 

 
Image Source –Google Search
 
There are many providers which give us more information on this available NO SQL in the market here.
 
These NO SQL databases differ from others due to the features. The characteristics which distinguish them is how to store the data. Some of them store the data by a document, some of them store the element by a key name, some of them store the data by graph or some of them are in the memory of NO SQL.

MongoDB is the most widely used NO SQL database because it manages high volumes of structured or non structured data and is faster in terms of processing, as well as efficient and scalable in nature.

Where NO SQL can be used

Consider an application -- when it goes to production, it works fine. After a few years down the line, the data keeps on growing and lots of performance issues come up. A lot of effort is required by the DBA and developers as to where to partition the data, rearrange the index, implement master and slave data, etc. Some portions of the system data are static (read only), and we can put in MongoDB like Master Database records. (Dropdown values in some cases).

The Product information and  product catalog,  which is static,  can be kept in MongoDB.

There are some external systems where we are not aware of what would be the nature of the data, such as XML, JSON, String, and binary information (Basically unstructured data).These record values can be kept in MongoDB.

NO SQL has not replaced RDBMS. RDBMS and NO SQL both can be used together to achieve a high performing system.  

We will learn here how to get MongoDB, how to store the data in MongoDB,  and how to do  some operations in MongoDB.

MongoDB is an open source NO SQL Database. The official website for MongoDB is here. To download MongoDB, go to the below URL and download the appropriate version of the operating system you have in your machine.



I have downloaded the highlighted version here.

The installation steps are very easy, just download the exe and click “next” and follow the screenshots, given below:

 
 
 
 
 



Once you install MongoDB, the folders with the path must have the files, given below:
 


In the root folder of installation, create a folder C:\data\db. In this path, MongoDB stores the data.



After the installation, go to the command prompt and go to the path “C:\Program Files\MongoDB\Server\3.2\bin”,

Type mongod command to start the database.



MongoDB has started now.



Basic Commands in MongoDB

Go to the command prompt and go to the path C:\Program Files\MongoDB\Server\3.2\bin

C:\Program Files\MongoDB\Server\3.2\bin>mongo

Now the screen will be shown, as given below:



In the test DB, I want to store some information into studentsInformation collection. The insert statement will be as follows:.

  1. db.studentsInformation.insert({StudentId : "1002",Name:"SMIT",Address:"45 Main st",City:"Compton", State:"LA",Country:"USA", Department:"CIVIL ENGINEERING", Marks:"90"})    


We have createda MongoDB database and inserted some data into it. Let’s create an ASP.NET Web page and see how to do some operations in it.

Go to Visual Studio, create an ASP.NET Web Application.

Add a dummy page named MongoDBOperation.aspx.

Go to Tool and then go to NuGet Package Manager Console and type “Install-Package mongocsharpdriver -Version 1.8.3”, given in the screenshot, below:

Once we install MongoDB Driver for C#, the required Dlls will be referred to in the project.

Fetching the data from MongoDB is as follows:

MongoDBOperation.aspx
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MongoDBOperation.aspx.cs" Inherits="MongoDBDemo.MongoDBOperation" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         .label {  
  10.             font-weight: bold;  
  11.             font-size: 15px;  
  12.         }  
  13.   
  14.         .Namecss {  
  15.             padding-left: 30px;  
  16.         }  
  17.     </style>  
  18. </head>  
  19. <body>  
  20.     <form id="form1" runat="server">  
  21.   
  22.         <div style="border: 2px solid gray; width: 900px;">  
  23.             <div>  
  24.                 <b>Student Information- Communicating to Mongo DB</b>  
  25.                 <hr />  
  26.                 <asp:GridView ID="grdStudentInformation" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="900px" AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged">  
  27.                     <AlternatingRowStyle BackColor="White" />  
  28.                     <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />  
  29.                     <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />  
  30.                     <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />  
  31.                     <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />  
  32.                     <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />  
  33.                     <SortedAscendingCellStyle BackColor="#FDF5AC" />  
  34.                     <SortedAscendingHeaderStyle BackColor="#4D0000" />  
  35.                     <SortedDescendingCellStyle BackColor="#FCF6C0" />  
  36.                     <SortedDescendingHeaderStyle BackColor="#820000" />  
  37.   
  38.                     <Columns>  
  39.                         <asp:BoundField DataField="_id" HeaderText="_id" ItemStyle-Width="30" />  
  40.                         <asp:BoundField DataField="StudentId" HeaderText="StudentId" ItemStyle-Width="30" />  
  41.                         <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" ItemStyle-CssClass="Namecss" />  
  42.                         <asp:BoundField DataField="Address" HeaderText="Address" ItemStyle-Width="100" />  
  43.                         <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="100" />  
  44.                         <asp:BoundField DataField="State" HeaderText="State" ItemStyle-Width="50" />  
  45.                         <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="50" />  
  46.                         <asp:BoundField DataField="Department" HeaderText="Department" ItemStyle-Width="100" />  
  47.                         <asp:BoundField DataField="Marks" HeaderText="Marks" ItemStyle-Width="50" />  
  48.                         <asp:TemplateField>  
  49.                             <ItemTemplate>  
  50.                                 <asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />  
  51.                             </ItemTemplate>  
  52.                         </asp:TemplateField>  
  53.                     </Columns>  
  54.                 </asp:GridView>  
  55.             </div>  
  56.             <table>  
  57.                 <tr>  
  58.                     <td class="label" colspan="3" style="padding-left: 50px;"><strong>Inserting Student Information to Mongo DB </strong></td>  
  59.                 </tr>  
  60.                 <hr />  
  61.                 <tr>  
  62.                     <td>  
  63.                         <asp:Label ID="lblStudentId" CssClass="label" runat="server" Text="Student Id"></asp:Label>  
  64.                         :</td>  
  65.                     <td>  
  66.                         <asp:TextBox ID="txtStudentId" runat="server" Width="151px"></asp:TextBox>  
  67.                     </td>  
  68.                     <td> </td>  
  69.                 </tr>  
  70.                 <tr>  
  71.                     <td>  
  72.                         <asp:Label ID="lblName" CssClass="label" runat="server" Text="Name"></asp:Label>  
  73.                         :</td>  
  74.                     <td>  
  75.                         <asp:TextBox ID="txtStudentName" runat="server" Width="151px"></asp:TextBox>  
  76.                     </td>  
  77.                     <td> </td>  
  78.                 </tr>  
  79.                 <tr>  
  80.                     <td>  
  81.                         <asp:Label ID="lblAddress" runat="server" CssClass="label" Text="Address"></asp:Label>  
  82.                         :</td>  
  83.                     <td>  
  84.                         <asp:TextBox ID="txtAddress" runat="server" Width="151px"></asp:TextBox>  
  85.                     </td>  
  86.                     <td> </td>  
  87.                 </tr>  
  88.                 <tr>  
  89.                     <td>  
  90.                         <asp:Label ID="lblcity" CssClass="label" runat="server" Text="City"></asp:Label>  
  91.                         :</td>  
  92.                     <td>  
  93.                         <asp:TextBox ID="txtCity" runat="server" Width="151px"></asp:TextBox>  
  94.                     </td>  
  95.                     <td> </td>  
  96.                 </tr>  
  97.                 <tr>  
  98.                     <td>  
  99.                         <asp:Label ID="lblState" runat="server" CssClass="label" Text="State"></asp:Label>  
  100.                         :</td>  
  101.                     <td>  
  102.                         <asp:TextBox ID="txtState" runat="server" Width="151px"></asp:TextBox>  
  103.                     </td>  
  104.                     <td> </td>  
  105.                 </tr>  
  106.   
  107.                 <tr>  
  108.                     <td>  
  109.                         <asp:Label ID="lblCountry" runat="server" CssClass="label" Text="Country"></asp:Label>  
  110.                         :</td>  
  111.                     <td>  
  112.                         <asp:TextBox ID="txtCountry" runat="server" Width="151px"></asp:TextBox>  
  113.                     </td>  
  114.                     <td> </td>  
  115.                 </tr>  
  116.                 <tr>  
  117.                     <td>  
  118.                         <asp:Label ID="lblDepartment" runat="server" CssClass="label" Text="Department"></asp:Label>  
  119.                         :</td>  
  120.                     <td>  
  121.                         <asp:TextBox ID="txtDepartment" runat="server" Width="151px"></asp:TextBox>  
  122.                     </td>  
  123.                     <td> </td>  
  124.                 </tr>  
  125.                 <tr>  
  126.                     <td>  
  127.                         <asp:Label ID="lblMarks" runat="server" CssClass="label" Text="Marks"></asp:Label>  
  128.                         :</td>  
  129.                     <td>  
  130.                         <asp:TextBox ID="txtMarks" runat="server" Width="151px"></asp:TextBox>  
  131.                     </td>  
  132.                     <td> </td>  
  133.                 </tr>  
  134.   
  135.                 <tr>  
  136.                     <td></td>  
  137.                     <td>  
  138.                         <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click" Text="Save " Width="128px" />  
  139.                     </td>  
  140.                     <td>  
  141.                         <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update " Width="128px" /></td>  
  142.                 </tr>  
  143.             </table>  
  144.         </div>  
  145.     </form>  
  146. </body>  
  147. </html>  

MongoDBOperation.aspx.cs

  1. using MongoDBDemo.Model;  
  2. using MongoDB.Bson;  
  3. using MongoDB.Driver;  
  4. using System;  
  5. using System.Configuration;  
  6. using System.Web.UI.WebControls;  
  7.   
  8.   
  9. namespace MongoDBDemo  
  10. {///  
  11.     public partial class MongoDBOperation : System.Web.UI.Page  
  12.     {  
  13.   
  14.         protected void Page_Load(object sender, EventArgs e)  
  15.         {  
  16.             string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString; // Get the connection string  
  17.             MongoServer server = MongoServer.Create(con); // Create the connection In MongoDB  
  18.             MongoDatabase myDB = server.GetDatabase("test"); // Get the Database where data ios there.  
  19.             MongoCollection<studentsInformation> Students = myDB.GetCollection<studentsInformation>("studentsInformation");// Get the Database collection where data is present.  
  20.                
  21.   
  22.             grdStudentInformation.DataSource = Students.FindAll();// Gettting the records using FindAll() method.  
  23.             grdStudentInformation.DataBind(); // Bind it to the grid.  
  24.         }  
  25.   
  26.         protected void btnSave_Click(object sender, EventArgs e)  
  27.         {  
  28.   
  29.             string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;  
  30.             MongoServer server = MongoServer.Create(con);  
  31.             MongoDatabase myDB = server.GetDatabase("test");  
  32.             MongoCollection<studentsInformation> collection = myDB.GetCollection<studentsInformation>("studentsInformation");  
  33.   
  34.             //Adding the element to the BsonDocument  after reading from UI Element.  
  35.   
  36.             BsonDocument newstudentInfo = new BsonDocument{  
  37.                     {"StudentId",txtStudentId.Text.ToString()},  
  38.                     {"Name",txtStudentName.Text.ToString()},  
  39.   
  40.                      {"Address",txtAddress.Text.ToString()},  
  41.                     {"City",txtCity.Text.ToString()},  
  42.   
  43.                      {"State",txtState.Text.ToString()},  
  44.                     {"Country",txtCountry.Text.ToString()},  
  45.   
  46.                      {"Department",txtDepartment.Text.ToString()},  
  47.                     {"Marks",txtMarks.Text.ToString()},  
  48.                 };  
  49.             collection.Insert(newstudentInfo);// Collection.Insert() is used to inset the records.  
  50.         }  
  51.   
  52.         protected void OnSelectedIndexChanged(object sender, EventArgs e)  
  53.         {  
  54.             GridViewRow row = grdStudentInformation.SelectedRow;  
  55.             ViewState["Idval"] = row.Cells[0].Text;  
  56.             txtStudentId.Text = row.Cells[1].Text;  
  57.             txtStudentName.Text = row.Cells[2].Text;  
  58.             txtAddress.Text = row.Cells[3].Text;  
  59.   
  60.             txtCity.Text = row.Cells[4].Text;  
  61.             txtState.Text = row.Cells[5].Text;  
  62.   
  63.             txtCountry.Text = row.Cells[6].Text;  
  64.             txtDepartment.Text = row.Cells[7].Text;  
  65.             txtMarks.Text = row.Cells[8].Text;  
  66.         }  
  67.   
  68.   
  69.         protected void btnUpdate_Click(object sender, EventArgs e)  
  70.         {  
  71.             string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;  
  72.             MongoServer server = MongoServer.Create(con);  
  73.             MongoDatabase myDB = server.GetDatabase("test");  
  74.             MongoCollection<studentsInformation> collection = myDB.GetCollection<studentsInformation>("studentsInformation");  
  75.             //Getting the Id where the BSONDocument will be updated.  
  76.             IMongoQuery query = MongoDB.Driver.Builders.Query.EQ("_id", ViewState["Idval"].ToString());  
  77.             IMongoUpdate update = MongoDB.Driver.Builders.Update.Set("StudentId", txtStudentId.Text.ToString())  
  78.                                                                    .Set("Name", txtStudentName.Text.ToString())  
  79.                                                                 .Set("Address", txtAddress.Text.ToString())  
  80.                                                                 .Set("City", txtCity.Text.ToString())  
  81.                                                                 .Set("State", txtState.Text.ToString())  
  82.                                                                 .Set("Country", txtCountry.Text.ToString())  
  83.                                                                  .Set("Department", txtDepartment.Text.ToString())  
  84.                                                                   .Set("Marks", txtMarks.Text.ToString());  
  85.             collection.Update(query, update);  // Collection.Update() is used to update the record.  
  86.         }  
  87.     }  
  88. }  


We saw MongoDB data interaction from an ASP.NET UI Page.

I hope you understood the basic concepts of NO SQL and how to use Mongo DB in an ASP.NET page. Thanks for your valuable time for reading it.


Similar Articles