Click here to Skip to main content
13,553,262 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


25 bookmarked
Posted 30 Jan 2012
Licenced CPOL

MongoDB with C#.NET

, 30 Jan 2012
Rate this:
Please Sign up or sign in to vote.
This article demonstrates how to get started with MongoDB in C#.NET


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.


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<bsondocument />("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 = 
    BsonDocument department = new BsonDocument {
                { "DepartmentName", departmentName },
                { "HeadOfDepartmentId", headOfDepartmentId }


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 = 
    BsonDocument employee = new BsonDocument {
                { "FirstName", firstName },
                { "LastName", lastName },
                { "Address", address },
                { "City", city },
                { "DepartmentId", departmentId }


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 = 
    foreach (Department department in departments.FindAll())

    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 = 

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.


  • 30th January, 2012: Initial version


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


About the Author

Software Developer (Senior) Support Services Company Ltd.
Pakistan Pakistan
Karachi - Pakistan.

You may also be interested in...

Comments and Discussions

QuestionGreat Article Pin
MohamedSoumare26-Jun-12 8:31
memberMohamedSoumare26-Jun-12 8:31 
AnswerRe: Great Article Pin
M-Idrees-pk26-Jun-12 19:07
memberM-Idrees-pk26-Jun-12 19:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180515.1 | Last Updated 30 Jan 2012
Article Copyright 2012 by Muhammad-Idrees-1
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid