Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Connecting MongoDB with ASP.NET

0.00/5 (No votes)
23 Oct 2013 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here