January 31, 2012

MongoDB in C#.net

Introduction

This article explain how to communicate with MongoDB from C#.net, providing an exmaple. I was looking for such sample example for MongoDB in C#.net, but after reasonable searching I not found some real practical tutorial showing complete example to communicate with MongoDB. Therefore I wrote this article to provide a complete sample to use MongoDB from C#.net for developers community who want to start with this new technology. So I put together that scattered information I founded on serveral sites to compile into some real practical sample application.

Background

There are some drivers available for communicating with MongoDB from C#.net, I prefer to use the official driver recommended available at github.com. So you must have download that driver and add references for the driver's essential libraries in your
project, such as :

  1. MongoDB.Bson.dll
  2. MongoDB.Driver.dll
At the time of executing this application, make sure that the MongoDB server is running.

Example

This sample application contains one form with different buttons :
  1. Create Data, Create sample data for Departments and Employees collections (keep remember, at first time you query any particular collection, mongoDb automatically create these collections if not already created).
  2. Get Departments, this will display the sample data created for departments colleciton, in the grid placed on the form.
  3. Get Employees, this will display the sample data created for employees colleciton, in the grid placed on the form.
  4. Delete Departments, this will delete all the departments available in the departments collection.
  5. Delete Employees, this will remove all the records available in the employees collection.
Let's start with the code. First define the connection string for your mongoDB server, by default its running on 27017 port, or you have to change it accordingly if you have specified something else. For example on my PC, I have server running on localhost at port 27017.

key="connectionString" value="Server=localhost:27017"

For create sample data, we use two methods CreateDepartment() and CreateEmployee(). Let first take a look at CreateDepartment method. It takes two parameters departmentName and headOfDepartmentId, which is practically should be the real head's Id, but for sampling here just any random Id is used. The core functionality of this method is :

  1. Connect to server: MongoServer.Create(ConnectionString) accepts the connection string for your server, and returns MongoServer type object, which later use to query the desired database object.
  2. Get Database: server.GetDatabase("MyCompany") this call returns MongoDatabase type object for the database used in this example MyCompany
  3. Retrieve departments collection: myCompany.GetCollection("Departments"), this method will actually retrieve our records from departments collection. It returns MongoCollection of passed generic type, BsonDocument
    in this case. At first time, definitely there will be no any departments present in the departments collection, so this collection object is empty(has 0 records).
  4. Create new department object: BsonDocument deptartment = new BsonDocument {}, this constructor syntax creates new department with the fields as you speficed in the constructor(remember MongoDB document could have different
    fields, not necessary that all documents have same fields)
  5. Insert document in departments collection: departments.Insert(deptartment), will actually insert the document in our departments collection.
private static void CreateDepartment(string departmentName, string headOfDepartmentId)
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");

 BsonDocument deptartment = new BsonDocument {
 { "DepartmentName", departmentName },
 { "HeadOfDepartmentId", headOfDepartmentId }
 };

 departments.Insert(deptartment);
}
Similarly CreateEmployee() method takes its parameters, connect to server, database, employee collection and insert employee in the collection. I follow the same flow to keep things clear for understanding.
private static void CreateEmployee(string firstName, string lastName,string address, string city, string departmentId)
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection employees = myCompany.GetCollection("Employees");
 BsonDocument employee = new BsonDocument {
 { "FirstName", firstName },
 { "LastName", lastName },
 { "Address", address },
 { "City", city },
 { "DepartmentId", departmentId }
 };

 employees.Insert(employee);
}
Next, we want to retrieve our recrods to display in the grid. We already look at retrieve code segment, just make a little changes here. Instead of BsonDocument I use my custom Department class which loaded collection of departments with my class objects. But make sure that the fields in the department collection must be exactly mapped in your Department class. Just calling GetCollection() method not actually retrieve the records, you need to call any desired method with query selectors (not covered in this aricle), so make things clear I just use simplest method FindAll() which rerieves all records from the given collection. Loop through each item and add in our temporary list which finally binds to our grid for display purpose. And I have followed the same theme to display employee records.
public static List GetDepartments()
{
 List lst = new List();
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");
 foreach (Department department in departments.FindAll())
 {
  lst.Add(department);
 }

 return lst;
}
The last thing we see here is the deletion of records. As we all know, deletion is the simplest job in most of the cases, and same here. After getting the MongoCollection object, you have to simply call its method Drop(), and it will simply delete all the records from that collection. You can also use query selectors in different methods to remove records selectively but that will be out of the scope of this article.
public static void DeleteDepartments()
{
 MongoServer server = MongoServer.Create(ConnectionString);
 MongoDatabase myCompany = server.GetDatabase("MyCompany");

 MongoCollection departments = myCompany.GetCollection("Departments");
 departments.Drop();
}
Once you get started with MongoDB you will enjoy exploring its dimensions. I found very interesting capabilities of MongoDB. I appreciate your feedback/comments or any improvements you want to suggest in this regard, to help in making the article much better and helpful for others.

Note: Source code for sample application could be found at my CodeProject post.

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time mongodb online training

    ReplyDelete