Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / MongoDB

Connecting .NET Application to MongoDB

4.57/5 (3 votes)
19 Nov 2013CPOL2 min read 35.5K   1.5K  
This tip shows how to connect with MongoDB from a .NET application.
Image 1

Introduction

This tip explains developing a .NET application which can connect to Mongo Database and perform various operations. This also touches slightly on Mongo Database and various commands.

Using the Code

Let's start with details about the Mongo database, basic commands and finally cover creating a .NET Windows application which connects to Mongo Database.

Mongo Database

MongoDB is a cross-platform document oriented database system which is classified as a "NoSQL" database. MongoDB avoids the traditional table based relational database structure and uses JSON like documents with dynamic schemas. MongoDB calls this format as BSON (Binary Json). This dynamic schema makes the integration of data in certain types of applications easier and faster. MongoDB is free and open source software.

Features of Mongo Database
  • Ad hoc queries
  • Indexing
  • Replication
  • Load balancing
  • File storage
  • Aggregation
  • Server-side JavaScript execution
  • Capped collections

Users can download Mongo Database from here and extract the contents to any folder. Once the file has been downloaded, user needs to configure data folder for MongoDB. For this, create a folder named "DB" within "C:\Data" folder.
Sample Image - maximum width is 600 pixels

Once the data folder has been created, Mongo database can be started by running "mongod.exe" command using a command prompt under "bin" folder.

Image 3

Now the database has been started and is running.

Creating a .NET Application

Create a .NET web/Windows application. In this example, we will utilize a simple employee table.

In order to start, we need to make sure that we have .NET driver for MongoDB available in the system. You can follow the below instructions to install the driver for a particular project.

Open package manager within Visual Studio:

Image 4

Once the package manager console has been opened, user can execute the below command:

Install-Package mongocsharpdriver

Image 5

Image 6

Add the reference to the below namespace to the project:

C#
using MongoDB.Bson;
using MongoDB.Driver;
//Additionally, you will frequently add one or more of these using statements:
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;

Declare variables for database server and database:

C#
MongoServer _server;
MongoDatabase _database;

Connect to database using the below command. Here the database server is running on local host with the port number : 27017 and database name is given as "anoop".

C#
private void Form1_Load(object sender, EventArgs e)
{
    string connection = "mongodb://localhost:27017";
    _server = MongoServer.Create(connection);
    _database = _server.GetDatabase("anoop", SafeMode.True);
}

Here, we have created 3 classes with different set of properties. We could fill the properties of these classes and can save the data to the same database and the same table. This is the real advantage of No-Schema database as it doesn't check schema while inserting the data. Each record can get saved with different set of fields and the other fields will be treated as NULL by default.

C#
public class Users1
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
public class Users2
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
}
public class Users3
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Location { get; set; }
}
private void rbEntity1_CheckedChanged(object sender, EventArgs e)
{
    txtName.Enabled = true;
    txtAge.Enabled = true;
    txtLocation.Enabled = true;
}
private void rbEntity2_CheckedChanged(object sender, EventArgs e)
{
    txtName.Enabled = true;
    txtAge.Enabled = false;
    txtLocation.Enabled = true;
}
private void rbEntity3_CheckedChanged(object sender, EventArgs e)
{
    txtName.Enabled = true;
    txtAge.Enabled = true;
    txtLocation.Enabled = false;
}
private void btnSave_Click(object sender, EventArgs e)
{
    if (rbEntity1.Checked)
    {
        var _users = _database.GetCollection<users3 />("users");
        var user = new Users3 { };
        user.Age = Convert.ToInt32(txtAge.Text);
        user.Name = txtName.Text;
        user.Location = txtLocation.Text;
        _users.Insert(user);
        var id = user.Id;
    }
    else if (rbEntity2.Checked)
    {
        var _users = _database.GetCollection<users2 />("users");
        var user = new Users2 { };
        user.Name = txtName.Text;
        user.Location = txtLocation.Text;
        _users.Insert(user);
        var id = user.Id;
    }
    else if (rbEntity3.Checked)
    {
        var _users = _database.GetCollection<users1 />("users");
        var user = new Users1 { };
        user.Age = Convert.ToInt32(txtAge.Text);
        user.Name = txtName.Text;
        _users.Insert(user);
        var id = user.Id;
    }
    MessageBox.Show("User with name " + txtName.Text + " created");
}
C#
///Below code helps you to finding an existing record from Mongo Database.
_collection = _database.GetCollection<users1 />("users");
IMongoQuery query = Query.EQ("Name", "Anoop");
Users1 _user = _collection.FindAs<users1 />(query).FirstOrDefault();
MessageBox.Show(_user.Age.ToString());
C#
///Below code helps you to update an existing record from Mongo Database.
_collection = _database.GetCollection<users1 />("users");
IMongoQuery query = Query.EQ("Name", "Anoop");
Users1 _user = _collection.FindAs<users1 />(query).FirstOrDefault();
MessageBox.Show("Age before update :" + _user.Age.ToString());
//Update age with some value
_user.Age = 30;
    
//Save the changes            
_collection.Save(_user);
MessageBox.Show("Age after update :" + _user.Age.ToString());

References

License

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