Working/Getting Started with Mongo DB and C# .NET

First of all lets describe what is Mongo DB and why it is used…
Advantages of using Mongo DB

  1. High Performance
  2. Highly Scalable
  3. High Availability

The only disadvantage mongo db has, is the disk space usage, which in these times is pretty cheap.

Mongo DB is a document based database, this means it stores collections of documents in a JSON/BSON format.

If you want to know more about mongo db check out this link:

http://www.mongodb.org/about/introduction/

First off we need to create a mongo database, MongoLab provides free hosting of a MongoDB (500mb maximum size)

https://mongolab.com/

Create an account with them, when done you can create a new database:

Now click “Create new mongodb deployment” and you’re done…

Click on the Database you created,

  1. Add a User
  2. Get the connection string for your database and change the connection string’s username and password with the User you created.

Important to note, don’t use special characters in your password because the connection string messes up when these characters are used. It is a known issue especially with the ‘@’ character.

Now create a new Visual Studio solution

In my case, I created a website MVC, anyway you can create any type of solution/project…

I also added a solution to put my data layer classes in it (more organized).

Now open Nuget and search for Mongo… you will find a package which includes the mongo db driver

When installed open up the references and note that two references were added, specifically the ones below:

Now we are good to go and start coding our way with C# and the Mongo Driver!

So first lets create a class which will represent an entity (collection) in our database, in this case I am going to create a simple entity Team (for a football team).

Note that the attributes which are used in the Team.cs class are attributes from MongoDB.Bson.Serialization.Attributes (libraries we added via nuget)

public class Team
    {
        /// <summary>
        /// This attribute is used to map the Id property to the ObjectId in the collection
        /// </summary>
        [BsonId]
        public ObjectId Id { get; set; }
 
        /// <summary>
        /// This is an attribute of my Team - in this case the team name
        /// </summary>
        [BsonElement("name")]
        public string Name { get; set; }
    }

Now we are going to need a class which manages our collections, in this case I am going to create a simple Connection class which could take as parameters the collection name and the type (in case you have more than a Team entity) Note, this is not the right way of doing it, in a real world scenario every class carries only its own responsibility. Anyway this tutorial was meant to show you how to communicate with MongoDB…

public class Connection
    {
        private string _connectionString;
        public MongoClient Entities { get; set; }
        public MongoServer Server { get; set; }
 
        private const string DatabaseName = "PUT DATABASE NAME HERE";
        public MongoDatabase Database { get; set; }
 
        public MongoCollection<Team> Teams { get; set; }
        public Connection()
        {
            _connectionString = "PUT CONNECTION STRING FROM MONGO LAB HERE - REPLACE username and password";
            if (Entities == null)
            {
                Entities = new MongoClient(_connectionString);
                Server = Entities.GetServer();
                Database = Server.GetDatabase(DatabaseName);
            }
        }
 
        public List<T> GetAll<T>(string collectionName)
        {
            var collection = GetCollectionOrCreateIfNotExistent<T>(collectionName);
            return collection.FindAllAs<T>().ToList();
        }
 
        public T Get<T>(string collectionName)
        {
            var collection = GetCollectionOrCreateIfNotExistent<T>(collectionName);
            return collection.FindOneAs<T>();
        }
 
        public void Add<T>(T entity, string collectionName)
        {
            var collection = GetCollectionOrCreateIfNotExistent<T>(collectionName);
            collection.Insert(entity);
        }
 
        /// <summary>
        /// This method will get the collection, if the collection is null it creates one for us - similar to a code first approach
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        private MongoCollection GetCollectionOrCreateIfNotExistent<T>(string collectionName)
        {
            var collection = Database.GetCollection<T>(collectionName);
            if (collection == null) Database.CreateCollection(collectionName);
            return collection;
        }
    }

Ok so read the inline comments I added to this class, where there are no comments, its because it is self explainable…

This is my current Solution’s structure:

As you can notice now I added a TeamController in my MVC Project which will handle the data procedures and render the views accordingly.

Note: make a Reference to your data project so you will be able to use the Connection Class we created

This is my TeamController code:

public class TeamController : Controller
    {
        public ActionResult Index()
        {
            Connection conn = new Connection();
            //Calling get all method
            var teams = conn.GetAll<Team>("teams");
            return View(teams);
        }
 
        public ActionResult Details(int id)
        {
            return View();
        }
 
        public ActionResult Create()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult Create(Team collection)
        {
            try
            {
                // TODO: Add insert logic here
                Connection conn = new Connection();
                //calling the add method
                conn.Add(collection, "teams");
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }

Ok let’s see if our code works as expected…

lets navigate to:

yourlocalhostaddress/Team   – Which calls our Index Action in the Team Controller (I already added two teams)

yourlocalhostaddress/Team/Create   – Which calls our Create Get Action in the Team Controller

And now we go back to our Team index and see our added team:


public class Team
    {
        /// <summary>
        /// This attribute is used to map the Id property to the ObjectId in the collection
        /// </summary>
        [BsonId]
        public ObjectId Id { get; set; }
 
        /// <summary>
        /// This is an attribute of my Team - in this case the team name
        /// </summary>
        [BsonElement("name")]
        public string Name { get; set; }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *