In this article, I would like to share a simple approach how to use C# connect to MongoDB database

Setup Environment

MongoDB installed on Ubuntu 14.04 LTS. Click here

Visual Studio 2015 Community is installed on Window 8 (VS2015)

MongoDB database

You have installed MongoDB successfully, then we connect to MongoDB to create a new collection of Users.

Step 1: connect to MongoDb via Putty tool. In this article, my MongoDB is installed on the virtual machine (VWareworkstation) within IP address 192.168.137.55

Step 2: create a new collection. We need this to make our application to be simple. Execute following commands from Putty after connecting to MongoDB successfully.

use Users

db.users.insert({“userid” : “test1” , “firstname” : “test” , “lastname” : “test”, “email” : “test1@test.com”, “address” : “test”})

The above commands is to create users collection in Users database. In this article, I inserted 3 documents.

Init_Data

 

Now, we’re ready to build a simple application following next steps.

.NET application – Load list of Users

Step 1: Create new window project in Visual Studio 2015 Community named as UserManagement

Step 2: We need install MongoDB drivers from VS2015. They are the libraries that allow us to connect and execute commands against MongoDB such as READ, INSERT, UPDATE, DELETE and so on.

Go to Tools -> Nuget Package Manager ->  Manage Nuget Packages Solution

Enter mongodb into Search box

MongoDB-Driver

We need to install 3 packages from NuGet

  • MongoDB.Bson
  • MongoDB.Driver
  • MongoDB.Driver.Core

Another way, you can download those packages from GitHub

Step 3: Add a Window Form item to the project named as UserManagementMaster

Step 4: Drag and drop TablControl component to UserManagementMaster form, named as tabUserManagement

Step 5: Create 2 TabPages on tabUserManagement tab control

  • tpUserList: tab page loads list of users from MongoDB . Drag and drop a button to tbUserList, when we click on this button, then connect to MongDB and then read list of users. Drag and drop DataGridView named as dtgvUserList.

UserList_TabPage

  • tpCreateNew: tab page creates a new user to insert into MongoDB. Drag and drop some textbox components as below.

CreateNew_TabPage

 

Step 6: Edit App.conf file to add connection string of MongoDB

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
<startup>
<supportedRuntime version=”v4.0″ sku=”.NETFramework,Version=v4.5″ />
</startup>
<connectionStrings>
<add name=”MongoDBConnection”
connectionString=”mongodb://192.168.137.55:27017/Users?connect=standalone“/>
</connectionStrings>
</configuration>

The syntax is mongodb://<IP of MongoDB host>:<Port of MongoDB>/<database name>?<option>

Step 7: Create new class User. This class will serve to store data of every document we read them from MongoDB

class User
{

public MongoDB.Bson.ObjectId _id { get; set; }
[MongoDB.Bson.Serialization.Attributes.BsonElement(“userid”)]
public MongoDB.Bson.BsonString UserID { get; set; }

[MongoDB.Bson.Serialization.Attributes.BsonElement(“firstname”)]
public MongoDB.Bson.BsonString FirstName { get; set; }

[MongoDB.Bson.Serialization.Attributes.BsonElement(“lastname”)]
public MongoDB.Bson.BsonString LastName { get; set; }

[MongoDB.Bson.Serialization.Attributes.BsonElement(“email”)]
public MongoDB.Bson.BsonString Email { get; set; }

[MongoDB.Bson.Serialization.Attributes.BsonElement(“address”)]
public MongoDB.Bson.BsonString Address { get; set; }

}

In front of each attribute of User class, we need to define [MongoDB.Bson.Serialization.Attributes.BsonElement(“<element name>”)]. We can back the section MongoDB database, we have inserted some documents that have structure as below

userid

firstname

lastname

email

address

So we need to map an attribute of the class to an element of the document in Users collection.

Step 7: Add MongoDB libraries which we have just installed at step 1

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Core;

Step 8: Load list of users. Double click on Load User button User List tab page.

private void btLoadUserList_Click(object sender, EventArgs e)
{
var ConnectionString = ConfigurationManager.ConnectionStrings[“MongoDBConnection”].ConnectionString;
var client = new MongoClient(ConnectionString);

DataTable dt = new DataTable();
dt.Columns.Add(“User ID”, typeof(string));
dt.Columns.Add(“First Name”, typeof(string));
dt.Columns.Add(“Last Name”, typeof(string));
dt.Columns.Add(“Email”, typeof(string));
dt.Columns.Add(“Address”, typeof(string));
try
{
var db = client.GetDatabase(“Users”);
var collection = db.GetCollection<User>(“users”);
var ul = collection.AsQueryable();

foreach (var item in ul)
{

var UserID = item.UserID;
var FirstName = item.FirstName;
var LastName = item.LastName;
var Email = item.Email;
var Address = item.Address;

dt.Rows.Add(UserID,
FirstName,
LastName,
BsonString.Equals(null, Email) ? “” : Email.ToString(),
BsonString.Equals(null, Address) ? “” : Address.ToString());

}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

//dt.DefaultView.Sort = “User ID ASC”;
dtgvUserList.DataSource = dt;
dtgvUserList.AllowUserToDeleteRows = true;

}

8.1 Create a new instance of MongoClient class, it will pass connection parameter which we declare in App.conf.

var client = new MongoClient(ConnectionString);

8.2 Get what database we want to query data

var db = client.GetDatabase(“Users”);

8.3 Get what collection of the database we get at step 8.2

var collection = db.GetCollection<User>(“users”);

8.4 Query all documents

var ul = collection.AsQueryable();

8.5 Loop in ul to read every document and then add to DataTable dt

foreach (var item in ul)
{

var UserID = item.UserID;
var FirstName = item.FirstName;
var LastName = item.LastName;
var Email = item.Email;
var Address = item.Address;

dt.Rows.Add(UserID,
FirstName,
LastName,
BsonString.Equals(null, Email) ? “” : Email.ToString(),
BsonString.Equals(null, Address) ? “” : Address.ToString());

}

8.6 Bind DataTable dt to DataGridView

dtgvUserList.DataSource = dt;
dtgvUserList.AllowUserToDeleteRows = true;

Step 9: Execute the program. The result shows 3 documents which we have inserted.

Load_UserList

.NET application – Create a new user

This step is to insert a new user into User collection

Step 1: Switch to tpCreateNew tab page and double click on Save button

Step 2: Insert a new users

private void btSave_Click(object sender, EventArgs e)
{
var ConnectionString = ConfigurationManager.ConnectionStrings[“MongoDBConnection”].ConnectionString;
var client = new MongoClient(ConnectionString);
var db = client.GetDatabase(“Users”);

var collection = db.GetCollection<BsonDocument>(“users”);

var u = new BsonDocument
{

{“userid” , txUserID.Text},
{“firstname” , txFirstName.Text },
{“lastname”,txLastName.Text},
{“email”,txEmail.Text},
{“address”, txAddress.Text}
};
try
{

collection.InsertOne(u);
MessageBox.Show(“Inserted data successfully”);

txUserID.Text = “”;
txFirstName.Text = “”;
txLastName.Text = “”;
txEmail.Text = “”;
txAddress.Text = “”;

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

2.1 Create a new instance of MongoClient class, it will pass connection parameter which we declare in App.conf.

var client = new MongoClient(ConnectionString);

2.2 Get what database we want to query data

var db = client.GetDatabase(“Users”);

2.3 Declare what collection of the database we get at step 2.2. within BsonDocument format

var collection = db.GetCollection<BsonDocument>(“users”);

2.4 Declare a new BsonDocument document and assign values from the text boxes.

var u = new BsonDocument
{

{“userid” , txUserID.Text},
{“firstname” , txFirstName.Text },
{“lastname”,txLastName.Text},
{“email”,txEmail.Text},
{“address”, txAddress.Text}
};

2.5 Insert data

collection.InsertOne(u);

Step 3: Execute program. We insert a new user and then reload list of users to see the result.

Insert_New_User

We have inserted test2 user successfully. Then we went to User List tab page to reload data. The result showed that test2 user is on the grid.

Reload_User_List

 

Conclusions

In this article, I am providing the simplest way to use C# to connect MongoDB. If you are a beginner of MongoDB world, hopefully you will find out the useful information to start with MongoDB. Obviously, we have many solutions which allow us to combine C# and MongoDB.

In case, you want to have the source code, please contact me.

Advertisements

5 thoughts on “.NET application and MongoDB

  1. The purpose of this line code is to create a connection to Mongodb server so you can put this line anywhere you want to start a connection. MongoClient class is available after you install Mongo packages which I mentioned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s