Click here to Skip to main content
15,896,118 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 104.8K   4.4K   26  
This article demonstrates how to get started with MongoDB in C#.NET
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDB2.Model
{
    /// <summary>
    /// Wrapper class to communicate with 'MyCompany' database.
    /// </summary>
    class MyCompany
    {
        public MyCompany()
        {

        }

        /// <summary>
        /// Connection string to the Mongo database server
        /// </summary>
        public static string ConnectionString
        {
            get
            {
                return ConfigurationManager.AppSettings["connectionString"];
            }
        }

        /// <summary>
        /// Creates sample data for two collections(or tables) i.e, Departments, Employees.
        /// </summary>
        public static void CreateData()
        {
            CreateDepartments();
            CreateEmployees();
        }
        
        #region Departments 

        /// <summary>
        /// Retrieve departments from MyCompany database.
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// Inserts sample departments data in MyCompany database
        /// </summary>
        private static void CreateDepartments()
        {
            string headOfDepartmentId;

            //insert department 'Development'
            headOfDepartmentId = "4f180083ef31ba0da8000010";
            CreateDepartment("Development", headOfDepartmentId);

            //insert department 'Accounts'
            headOfDepartmentId = "4f180083ef31ba0da8000011";
            CreateDepartment("Accounts", headOfDepartmentId);

            //insert department 'Human Resource'
            headOfDepartmentId = "4f180083ef31ba0da8000012";
            CreateDepartment("Human Resource", headOfDepartmentId);
        }

        /// <summary>
        /// Insert the department
        /// </summary>
        /// <param name="departmentName"></param>
        /// <param name="headOfDepartmentId"></param>
        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 deptartment = new BsonDocument {
                        { "DepartmentName", departmentName },
                        { "HeadOfDepartmentId", headOfDepartmentId }
                        };

            departments.Insert(deptartment);
        }

        /// <summary>
        /// Delete all data in departments collection in MyCompany database
        /// </summary>
        public static void DeleteDepartments()
        {
            MongoServer server = MongoServer.Create(ConnectionString);
            MongoDatabase myCompany = server.GetDatabase("MyCompany");

            MongoCollection<Department> departments = myCompany.GetCollection<Department>("Departments");
            departments.Drop();
        } 
        #endregion

        #region Employees 

        /// <summary>
        /// Retrieve employees from MyCompany database.
        /// </summary>
        /// <returns></returns>
        public static List<Employee> GetEmployees()
        {
            List<Employee> lst = new List<Employee>();

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

            MongoCollection<Employee> employees = myCompany.GetCollection<Employee>("Employees");
            foreach (Employee employee in employees.FindAll())
            {
                lst.Add(employee);
            }

            return lst;
        }

        /// <summary>
        /// Inserts sample employees data in MyCompany database
        /// </summary>
        private static void CreateEmployees()
        {
            // add 5 sample Employees
            for (int i = 1; i <= 5; i++)
            {
                string departmentId = "4f180083ef31ba0da8000010";
                CreateEmployee("FirstName" + i, "LastName" + i, "Address" + i, "City" + i, departmentId);
            }
        }

        /// <summary>
        /// Insert the employee
        /// </summary>
        /// <param name="departmentName"></param>
        /// <param name="headOfDepartmentId"></param>
        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);
        }

        /// <summary>
        /// Delete all data in employees collection in MyCompany database
        /// </summary>
        public static void DeleteEmployees()
        {
            MongoServer server = MongoServer.Create(ConnectionString);
            MongoDatabase myCompany = server.GetDatabase("MyCompany");

            MongoCollection<Employee> employees = myCompany.GetCollection<Employee>("Employees");
            employees.Drop();
        } 
        #endregion
    }

    #region Department 
    /// <summary>
    /// Department represents a single item(record) stored in Departments collection.
    /// </summary>
    class Department
    {
        public ObjectId _id { get; set; }
        public string DepartmentName { get; set; }
        public ObjectId HeadOfDepartmentId { get; set; }
    } 
    #endregion

    #region Employee 
    /// <summary>
    /// Department represents a single item(record) stored in Employees collection.
    /// </summary>
    class Employee
    {
        public ObjectId _id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public ObjectId DepartmentId { get; set; }
    } 
    #endregion
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

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