Click here to Skip to main content
Click here to Skip to main content

Connecting MongoDB with ASP.NET

, 23 Oct 2013
Rate this:
Please Sign up or sign in to vote.
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.

  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…

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

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.

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>’.

  <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.
        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.
    List<Info> names = new List<Info>();

    Create an instance of MongoServer using the connection string.

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

    Get the database name:

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

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

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

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

    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:

    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

License

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

Share

About the Author

gypsyShovan

Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun16-Apr-14 19:29 
SuggestionConnection closure is not available Pinmembermannu80801-Jan-14 23:47 
GeneralMy vote of 5 PinmemberM Rayhan12-Dec-13 0:04 
Questionvote 5 Pinmemberlizhong huang21-Nov-13 16:06 
QuestionA suggestion PinmemberGeorge Swan23-Oct-13 20:46 
AnswerRe: A suggestion PinmembergypsyCoder25-Oct-13 1:12 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140821.2 | Last Updated 23 Oct 2013
Article Copyright 2013 by gypsyShovan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid