Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

MongoDB with C#.NET

Rate me:
Please Sign up or sign in to vote.
4.75/5 (9 votes)
30 Jan 2012CPOL4 min read 104K   4.4K   26   13
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<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.
C#
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.

C#
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.

C#
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Support Services Company Ltd.
Pakistan Pakistan
Karachi - Pakistan.
http://idreesdotnet.blogspot.com/

Comments and Discussions

 
QuestionThanks Pin
yousef.emdadi26-Oct-14 22:10
yousef.emdadi26-Oct-14 22:10 
Questionperformnce of mongo Pin
Pradeep deepu 223-Aug-14 8:54
Pradeep deepu 223-Aug-14 8:54 
QuestionNIce Article ....it was helpful and simple Pin
heemanshubhalla10-Apr-14 5:06
heemanshubhalla10-Apr-14 5:06 
QuestionMONGODB-C#.NET Pin
bakkupavan5-Aug-13 4:33
bakkupavan5-Aug-13 4:33 
AnswerRe: MONGODB-C#.NET Pin
Muhammad Idrees GS5-Aug-13 21:57
Muhammad Idrees GS5-Aug-13 21:57 
QuestionGreat Article Pin
MohamedSoumare26-Jun-12 8:31
MohamedSoumare26-Jun-12 8:31 
AnswerRe: Great Article Pin
Muhammad Idrees GS26-Jun-12 19:07
Muhammad Idrees GS26-Jun-12 19:07 
QuestionCan I get rid of this server? Pin
Ashraf Sabry2-Mar-12 5:53
Ashraf Sabry2-Mar-12 5:53 
AnswerRe: Can I get rid of this server? Pin
Muhammad Idrees GS4-Mar-12 18:44
Muhammad Idrees GS4-Mar-12 18:44 
Simply not,

MongoDb is not targeted to use as embedded database. SQLCe is much better option, you already know, what's wrong with that ?

Moreover there are some other options as well, you could use as embedded databases :
Firebird embedded database
VelocityDB
GeneralRe: Can I get rid of this server? Pin
Ashraf Sabry4-Mar-12 18:53
Ashraf Sabry4-Mar-12 18:53 
AnswerRe: Can I get rid of this server? Pin
Geni14-Mar-12 3:31
Geni14-Mar-12 3:31 
GeneralRe: Can I get rid of this server? Pin
Ashraf Sabry14-Mar-12 4:39
Ashraf Sabry14-Mar-12 4:39 
GeneralRe: Can I get rid of this server? Pin
Muhammad Idrees GS14-Mar-12 19:25
Muhammad Idrees GS14-Mar-12 19:25 

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.