Getting Started With MongoDB and ASP.Net

 

 

 

Introduction

This article shows how to install MongoDB in Windows and communicate using ASP.NET. We will create a simple ASP.NET application that retrieves data from MongoDB.

Create a simple ASP.NET application that retrieves data. You can have a look at my other articles of MongoDB from here.

Installing Mongo db  

Installing MongoDB in Windows is very easy and simple. Use the following procedure to get it running:

       1.     Download MongoDB for Windows from "http://www.mongodb.org/downloads". 

2.     After downloading, create a folder named MongoDB and extract the Zip file into that folder.                        

That’s all. MongoDB is now installed. We can find many files in the folder but the key files are:

  •  mongod.exe: The Mongo database
  • mongo.exe:  The administrative shell
  • Mongos.exe: The sharding controller (Sharding is the process of storing data records across multiple machines and is MongoDB’s approach to meeting the demands of data growth.)

Now let's get started by setting up the server and creation of a database; use the following procedure to do that.

  • Step 1: Open the command prompt in administrator mode as shown and go to the MongoDB’s directory. (The folder where we extracted the Zip contentto.) For mine, the folder name is mongodb.

 

 

 

  • Step 2 :Type "mongod" and press Enter. And MongoDB has started. It uses port 27017 by default as shown below.

 

 

 

  • Step 3: Now open another command prompt and go to mongodb’s directory. Type "mongo". This command will connect to the default test database.

      MongoDB is schemaless and contains no table or relation. It maintains a collection of data. So, for now to keep things simple, Let's create a “Students” collection in the “test” database with a student “studentId = P1 and Name = Anonymous”. Just type the following command:

 

1. db.students.insert({studentId: "P1",Name:"Anonymous"})  

 

 

Let's check whether or not the students collection was created by issuing the command: 

show collections

 


 

 Let us find the data in the collection by issuing: 

 db.students.find() 

 

 

We can see our data in the collection.

Now let's us retrieve the data using an ASP.NET application.

Create an ASP.NET application and and add the mongocsharpdriver using the package manger console as shown below.

Install-Package mongocsharpdriver

 
 
 
Now let's  define the connection string for the MongoDB server. By default, it runs on the port 27017, So, define the connection string inside the "web.config" file as in the following:
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!--  
  3.   For more information on how to configure your ASP.NET application, please visit  
  4.   http://go.microsoft.com/fwlink/?LinkId=169433  
  5.   -->  
  6. <configuration>  
  7.   <system.web>  
  8.     <compilation debug="true" targetFramework="4.5" />  
  9.     <httpRuntime targetFramework="4.5" />  
  10.   </system.web>  
  11. <appSettings>  
  12.     <add key="connectionString" value="Server=localhost:27017"/>  
  13.   </appSettings>  
  14. </configuration>  

Our application is now ready to communicate with the MongoDB.

Now create a helping class named "studentinfo" that contains "_id" that one is an ObjectId type and uses MongoDB.Bson, studnetId and Name; all are string type. 

  1. using MongoDB.Bson;  
  2.   
  3. namespace MongowithAsp  
  4. {  
  5.     public class studentsinfo  
  6.     {  
  7.         public ObjectId _id { getset; }  
  8.         public string studentId { getset; }  
  9.         public string Name { getset; }  
  10.     }  
  11. }  
 
 Now, create a simple button and a label as shown below:
 
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="retreivedata.aspx.cs" Inherits="MongowithAsp.retreivedata" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>ASP.NET with Mongo</title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.         <h1> </h1>  
  13.         <asp:Button ID="showButton" runat="server" Text="Show Students" OnClick="showButton_Click" />  
  14.     </div>  
  15.         <asp:Label ID="nameLabel" runat="server"></asp:Label>  
  16.     </form>  
  17. </body>  
  18. </html>  
And write the following code for the button click event:
 
  1. using MongoDB.Driver;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Configuration;  
  5.   
  6. namespace MongowithAsp  
  7. {  
  8.     public partial class retreivedata : System.Web.UI.Page  
  9.     {  
  10.         string name = "";  
  11.         protected void Page_Load(object sender, EventArgs e)  
  12.         {  
  13.   
  14.         }  
  15.   
  16.         protected void showButton_Click(object sender, EventArgs e)  
  17.         {  
  18.             List<studentsinfo> names = new List<studentsinfo>();  
  19.             MongoServer server = MongoServer.Create(ConfigurationManager.AppSettings["connectionString"]);  
  20.             MongoDatabase myDB = server.GetDatabase("test");  
  21.             MongoCollection<studentsinfo> Students = myDB.GetCollection<studentsinfo>("students");  
  22.             foreach (studentsinfo Astudent in Students.FindAll())  
  23.             {  
  24.                 namename = name + " " + Astudent.Name;  
  25.                 names.Add(Astudent);  
  26.             }  
  27.             namenameLabel.Text = name;  
  28.         }  
  29.     }  
  30. }  
We have created an instance of MongoServer using the connection string and by iterating through the collection, we are getting the individual student and adding it in the "names" list.
 
 
 Let's debug to check the output.
 
 
 
 Summary
 
In this article we saw how to use MongoDB with an ASP.NET application. I hope you have understood how easy it is to access MongoDB in an ASP.NET application. 
 

Up Next
    Ebook Download
    View all
    Learn
    View all