Saturday, 12 September 2015

What is MongoDB and how it differs from RDMS ? USING MongoDB with Visual studio and C#

ASSUMPTION:You have basic knowledge of Sql and c# and you have created already user table(collection ) in mongodb.
2. You have downloaded mongodb driver . I choose N-Get package manager. here is screen shot of how to refer mongodb driver


3.Set references to your visual studio project like shown below

INTRODUCTION:Let us just recall how our traditional RDBM looks like, It is just based on tables made of rows and columns.Similarly  mongoDB are based on collection of documents, with each of these documents consisting of key/value attributes(JSON format).  A single document can be thought of as the equivalent of a row in a table, with each key being similar to a column name and each key’s value being similar to the respective row’s value.
Here is the view of database collection where four rows(documents) are saved





The exact difference being that a document is not constrained to a certain schema or columns within a table.  Two documents can share similar elements, like an ID field, as well as having completely different elements.   Data representation in both look like shown below

RDBMS NOSQL
.
.

just to recap, MongoDB is made up of databases which contain collections. A collection in turn is made up of documents.Each document is made up of fields. Collections can be indexed, which improves lookup and sorting performance.  The core difference is that relational databases define columns at the table level whereas a document-oriented database defines its fields at the document level. 
In MongoDB, the data structure and hierarchy are like:
Databases
   Collections
      Documents
         Fields
A field is a key-value pair. A key is a name (string). A value is a basic type like string, integer, float, time-stamp, binary, etc., or a document, or an array of values.
Conclusively you can say, collections are made of JSON-like documents. This is the main difference from traditional RDBM.
Note: The  BSON  is a binary-encoded serialization of J SON-like documents.It is just lightweight, traversable, and efficient.

Why MongoDB

MongoDB is an open-source document database that provides high performance, high availability, and automatic scaling what else you need if your business data is huge or growing fast ?

IMPORTANT CONCEPTS

  • A database can have zero or more collections. A collection shares enough in common with a traditional table that you can safely think of the two as the same thing.
  • Collections are made up of zero or more documents. Again, a document can safely be thought of as a row.
  • a lot like columns.
  • Indexes in MongoDB function mostly like their RDBMS(oracle sql server,sybase) counterparts.

The Benefits of NoSQL

  • Large volumes of structured, semi-structured, and unstructured data
  • Agile sprints, quick iteration, and frequent code pushes
  • Object-oriented programming that is easy to use and flexible
  • Efficient, scale-out architecture instead of expensive, monolithic architecture

Windows Platform Support

Starting from MongoDB version 2.2, MongoDB doesn’t support Windows XP. So if you are on Windows XP, either upgrade it or use the lower versions of MongoDB. This tutorial is intended to help you in installing MongoDB on Windows latest versions i.e Windows 7 and Windows 8, 8.1 etc.

Installation of MongoDB on Windows

Follow below steps to perform the installation of MongoDB into your windows system.
  1. Consider specific MongoDB build type which you need actually Three build types of MongoDB for Windows are available.
MongoDB for Windows Server 2008 R2 series: This build type runs only on 2008R2, Windows 7 64-bit, Windows 8, and latest versions of Windows.
MongoDB for Windows 64-bit: This build type of MongoDB runs on any 64-bit version of Windows latest than Windows XP, involve Windows Server 2008 R2 and Windows 7 64-bit.
MongoDB for Windows 32-bit: MongoDB runs on any 32-bit version of Windows latest than Windows XP, 32-bit version of MongoDB are only designed for older system and use for testing and developing systems. Windows 32-bit versions of MongoDB support only database smaller than 2GB.



  • Download MongoDB for Windows
  • download the latest version release from the MongoDB Download page. Make sure you download the latest version of MongoDB for your Windows. Note that 64-bit versions of MongoDB do not run with 32-bit Windows.
  • MongoDB installation folder move to another location (Optional) Sometimes we want to move the installation to another directory, we can use move command for this. This command needs to be run as administrator. For example, to move the folder to C:\MongoDB follow the steps shown in below images.
  • MongoDB does not depend at any other system because it is self contained. You can execute MongoDB from the folder of your choice and can install it in any folder (for, me it is programFiles folder like C:\Program Files\MongoDB\Server\3.0\bin)

    Running MongoDB Server

    We need to create a directory where MongoDB server will store all it’s data. The MongoDB default data directory path is \data\db. Make this folder using the following commands from Command Prompt. Note that if the directory doesn’t exists, MongoDB will try to create it. But it’s good to create it before hand.
    Microsoft Windows [Version 6.3.9600]
    (c) 2013 Microsoft Corporation. All rights reserved.
    C:\>md \data\db

    To start MongoDB server, we need to run mongod.exe just fallow below listed commands





    Note: I am setting path just to run mongodb from c drive every time rather than going to installation folder every time
    This MongoDB starts the main databases process. The waiting for connection message in the console results determines that the mongod.exe process is complete.

    you will see below







    You can use a different path for data files using the –dbpath option to mongod.exe, for example:

    Getting Started with MongoDB and C#

    So, let’s get started!

    EXAMPLE:

    In the MongoDB world, the Document class is the center of it’s universe. Because the very concept of the database is built upon the concept of this document, this is what you’ll find yourself using most. You use them to insert data, update data, delete data, query data. You will find it easy
    Here’s where I’m going to write code it do some database related operations like INSERT UPDATE SELECT..
    Here you see
    Please note that i am not fallowing coding best practice just for the sake of making code more understandable.
    CODE BEHIND FILE

    using MongoDB.Bson;
    using MongoDB.Bson.IO;
    using MongoDB.Bson.Serialization;
    using MongoDB.Bson.Serialization.Serializers;
    using MongoDB.Driver;
    using MongoDB.Driver.Builders;
    using System;
    using System.Configuration;
    using System.Globalization;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    namespace AspAppwithMongoDb
    {
    public partial class _Default : Page
    { 
    protected void Page_Load(object sender, EventArgs e)
    { 
    
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName); 
    //get mongodb collection
    var collection = myUser.GetCollection<User>("User");
    //document just like record/row in rdbms
    BsonDocument doc = new BsonDocument();
    doc["FirstName"] = txtFirstName.Text;
    doc["lastname"] = txtLastName.Text;
    collection.Insert(doc);
    lblSuccess.Text = "Saved Successfully";
    }
    
    protected void btnView_Click(object sender, EventArgs e)
    {
    
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName); 
    MongoCollection<User> Users =
    myUser.GetCollection<User>("User");
    nameLabel.Text = nameLabel.Text + "<table class='table'><thead><th>First Name</th><th>Last Name</th></thead>";
    foreach (User usr in Users.FindAll())
    {
    nameLabel.Text = nameLabel.Text + "<tr>";
    nameLabel.Text = nameLabel.Text + "<td>" + usr.FirstName + "</td>";
    nameLabel.Text = nameLabel.Text + "<td>" + usr.lastname + "</td>";
    nameLabel.Text = nameLabel.Text + "</tr>";
    }
    nameLabel.Text = nameLabel.Text + "</table>"; 
    }
    
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
    //Get Connection Details 
    var strConn = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
    var server = MongoServer.Create(strConn);
    // Create a myUser object from database by using the connection string 
    MongoDatabase myUser = server.GetDatabase(strConn.DatabaseName);
    var collection = myUser.GetCollection<User>("User");
    var update = new UpdateDocument { 
    { "$set", new BsonDocument("lastname",txtLastName.Text) } };
    
    var query = new QueryDocument { {"lastname", "" } };
    collection.Update(query, update);
    
    lblSuccess.Text = "Updated Successfully";
    }
    
    }
    public class User
    {
    public ObjectId _id { get; set; }
    public string FirstName { get; set; }
    public string lastname { get; set; }
    } 
    }

    ASPX PAGE


    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="AspAppwithMongoDb._default" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <style>
    table{
    width:50%;
    border:1px solid #f2f2f2;
    padding:5px;
    }
    
    </style>
    <asp:Literal ID="nameLabel" runat="server"></asp:Literal>
    <br />
    
    <table>
    <tr><td class="auto-style1">
    <asp:Button ID="btnView" runat="server" Text="View Records" OnClick="btnView_Click" />
    </td><td class="auto-style1" colspan="2">&nbsp;</td></tr>
    <tr><td>FirstName</td><td colspan="2"> <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td></tr>
    <tr><td>LastName</td><td colspan="2"> <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td></tr>
    <tr><td>&nbsp;</td><td colspan="2"> 
    <asp:Label ID="lblSuccess" runat="server" ForeColor="#33CC33"></asp:Label>
    </td></tr>
    <tr><td>&nbsp;</td><td colspan="2"> <asp:Button ID="btnSave" runat="server" Text="Save Record" OnClick="btnSave_Click" /> 
    </td></tr>
    <tr><td>
    First Name Update</td><td>
    <asp:TextBox ID="txtupdatefirstname" runat="server"></asp:TextBox>
    &nbsp;New FirsName</td><td>
    <asp:TextBox ID="txtupdatefirstnameto" runat="server"></asp:TextBox>
    </td></tr>
    
    <tr><td>
    &nbsp;</td><td>
    &nbsp;</td><td>
    <asp:Button ID="btnUpdate" runat="server" Text="Update Record" OnClick="btnUpdate_Click" />
    </td></tr>
    
    </table>
    </div>
    </form>
    </body>
    </html>
    
    WEBCIONFIG.XML




    Using MongoVUE Is just like SQL Management tool which help you to handle database operation using GUI

    A nice GUI makes it easy. Fortunately  for us MongoVUE exists and provides a very pleasant SQL Management Studio like experience over MongoDB
    First download and install MongoVUE.

    Next, run MongoVUE and connect to the default “local” connection. Once connected you should see a User . If you double click the Club node a table view will be rendered, expand the first document to see its data:






    Or click Text View to see the raw document.if you are interested in learning more of its features, read through its tutorials.

    Hope this helps

    Shabir Hakim

    1 comment:

    How to Build a Full-Stack Web App with Blazor

      Blazor Stack Overview Important Points: Blazor stack gives you options to create Web Applications without writing JavaScript (doesn't ...