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

Connecting MongoDB with ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.93/5 (17 votes)
23 Oct 2013CPOL3 min read 91.1K   2.2K   37   9
A startup ASP.NET application using MongoDB

Introduction

This article shows how to install MongoDB in Windows and communicate using ASP.NET. The simple ASP.NET application retrieves data from MongoDB.

Installing MongoDB

Installing MongoDB in Windows is a very easy task. Just follow the steps below to get it running:

  • Download MongoDB for Windows from "http://www.mongodb.org/downloads".
    64-bit 2008R2+ is useful because it uses a Windows API called 'slim'. 64-bit 2008R2+ requires WINDOWS SERVER 2008 R2 and higher and WINDOWS 7 and higher. If you do not meet the requirements, use other
    releases. The even numbers for the middle digits indicate the stable releases.
  • After downloading the .zip file, extract it. Inside, there is a bin folder.
  • In C: directory, create a folder, rename it and copy all files from bin folder into this folder.

That’s all. MongoDB is now installed. There are a bunch of files in the folder but the key files are…

  1. mongod.exe: The Mongo database
  2. mongo.exe: The administrative shell
  3. Mongos.exe: The sharding controller
Now we are going to start the MongoDB and create a database...
  1. Open the command prompt and go to the mongodb’s directory (The folder where you copied the bin folder’s content). For mine, the folder name is ‘mongodb2_4’.
  2. Write ‘mongod’ and press Enter. And MongoDB has started. It used port “27017” by default.

    Image 1

  3. Now open another command prompt and go to mongodb’s directory. Enter “mongo localhost\test”. This command will simply create test database.

MongoDB is schemaless and contains no table or relation. It maintains collection of data. So, for now to keep things simple, we are going to create a “Persons” collection in “test” database with a person “personId = P1 and Name = Anonymous”. Just write the following command…

SQL
db.persons.insert({personId:"P1",Name:"Anonymous"})

Image 2

So, now test database contains “Persons” collection with a person.

Using the Code

This simple ASP.NET application contains ‘create.aspx’ page with a button and a label.

At first, add “mongocsharpdriver” from nuget using package manager console.

Image 3

We have to define the connection string for MongoDB server. By default, it runs on 27017 port, you have to change it if you have specified something else. So, add the following code to the ‘web.config’ file inside ‘<configuration></configuration>’.

XML
<appSettings>
  <add key="connectionString" value="Server=localhost:27017"/>
</appSettings>

Now, our application is ready to communicate with the MongoDB.

Show Names’ button’s click event is going to retrieve data from ‘test’ database’s ‘Persons’ collection. To do this, let us do the following tasks...

  1. Create helping class: ‘info’ class contains _id which one is ObjectId type and uses MongoDB.Bson, personId, Name both are string type.
    C#
    public class Info
    {
        public ObjectId _id { get; set; }
        public string personId { get; set; }
        public string Name { get; set; }
    }
    
  2. Get Data: Inside Show Names button’s click event lets us declare a List ‘names’ of ‘Info’ class type.
    C#
    List<Info> names = new List<Info>();

    Create an instance of MongoServer using the connection string.

    C#
    MongoServer server = MongoServer.Create(ConfigurationManager.AppSettings["connectionString"]);

    Get the database name:

    C#
    MongoDatabase myDB = server.GetDatabase("test");  

    Now, we are ready to have the ‘persons’ collection from ‘test’ database:

    C#
    MongoCollection<Info> Persons = myDB.GetCollection<Info>("persons");

    Iterating through the collection, we are getting the individual person and adding it in the ‘names’ list:

    C#
    foreach(Info Aperson in Persons.FindAll())
                {
                    name = name+" "+Aperson.Name;
                    names.Add(Aperson);
                }

    For simplicity, we are only taking the names from the collection and showing it using the nameLabel:

    C#
    nameLabel.Text = name; 

Points of Interest

This one is just a startup with MongoDB in ASP.NET. Jump into the schemaless world of Mongo. I am amazed with it’s amazing capability.

History

  • 20th September, 2013: Initial version
This article was originally posted at http://www.babycoders.com?p=66

License

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


Written By
Software Developer Cefalo
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 3 Pin
Donsw6-Jan-16 8:15
Donsw6-Jan-16 8:15 
QuestionQuestion Pin
vyloc8-Jun-15 8:14
vyloc8-Jun-15 8:14 
AnswerRe: Question Pin
vigorniensis9-Jun-15 1:00
professionalvigorniensis9-Jun-15 1:00 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun16-Apr-14 19:29
Humayun Kabir Mamun16-Apr-14 19:29 
SuggestionConnection closure is not available Pin
mannu80801-Jan-14 23:47
mannu80801-Jan-14 23:47 
GeneralMy vote of 5 Pin
M Rayhan12-Dec-13 0:04
M Rayhan12-Dec-13 0:04 
Questionvote 5 Pin
lizhong huang21-Nov-13 16:06
lizhong huang21-Nov-13 16:06 
QuestionA suggestion Pin
George Swan23-Oct-13 20:46
mveGeorge Swan23-Oct-13 20:46 
Thanks for the tip. It may not be a good idea to create a new server and database instance for each button-click event. These methods are quite intensive and a lot of processing time will be saved by not repeatedly opening the server and database. I would suggest that the page-load event handler is a better location for these operations. Best wishes, George.
AnswerRe: A suggestion Pin
Paul Shovan25-Oct-13 1:12
Paul Shovan25-Oct-13 1:12 

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

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