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

MongoDB with C#.NET

0.00/5 (No votes)
30 Jan 2012 1  
This article demonstrates how to get started with MongoDB in C#.NET

Introduction

This article explains how to communicate with MongoDB from C#.NET, providing an example. I was looking for such a sample example for MongoDB in C#.NET, but after reasonable searching I did not find any real practical tutorial showing a complete example to communicate with MongoDB. Therefore, I wrote this article to provide a complete sample to use MongoDB from C#.NET for the developer community who wants to start with this new technology. So I put together that scattered information I founded on several sites to compile into a 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 here. So you must 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.

Using the Code

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 collection, in the grid placed on the form.
  3. Get Employees, this will display the sample data created for employees collection, 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 it's 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 creating 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 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 is later used to query the desired database object.
  2. Get Database: server.GetDatabase("MyCompany") 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. The 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 department = new BsonDocument {}, this constructor syntax creates a new department with the fields as you specified in the constructor (remember MongoDB document could have different fields, not necessary that all documents have the 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<BsonDocument> departments = 
        myCompany.GetCollection<BsonDocument>("Departments");
    BsonDocument department = new BsonDocument {
                { "DepartmentName", departmentName },
                { "HeadOfDepartmentId", headOfDepartmentId }
                };

    departments.Insert(deptartment);
}

Similarly CreateEmployee() method takes its parameters, connects to server, database, employee collection and inserts 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<BsonDocument> employees = 
        myCompany.GetCollection<BsonDocument>("Employees");
    BsonDocument employee = new BsonDocument {
                { "FirstName", firstName },
                { "LastName", lastName },
                { "Address", address },
                { "City", city },
                { "DepartmentId", departmentId }
                };

    employees.Insert(employee);
}

Next, we want to retrieve our records to display in the grid. We already look at retrieve code segment, just make a few 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 article), so to make things clear, I just use the simplest method FindAll() which retrieves 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<Department> GetDepartments()
{
    List<Department> lst = new List<Department>();

    MongoServer server = MongoServer.Create(ConnectionString);
    MongoDatabase myCompany = server.GetDatabase("MyCompany");

    MongoCollection<Department> departments = 
        myCompany.GetCollection<Department>("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<Department> departments = 
        myCompany.GetCollection<Department>("Departments");
    departments.Drop();
} 

Points of Interest

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.

History

  • 30th January, 2012: 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