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:
- MongoDB.Bson.dll
- 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:
- 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).
- Get Departments, this will display the sample data created for
departments
collection, in the grid placed on the form.
- Get Employees, this will display the sample data created for
employees
collection, in the grid placed on the form.
- Delete Departments, this will delete all the
departments
available in the departments
collection.
- 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:
- 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.
- Get Database:
server.GetDatabase("MyCompany")
call returns MongoDatabase
type object for the database used in this example MyCompany.
- 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).
- 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)
- 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