How to add and alter table in MongoDB using C#

In earlier post Connecting to MongoDB database using .Net in MVC application I described the basic requirements to get started with using MongoDB in your C# MVC application. Now I will start discussing some basic CRUD operations that you will be performing in your database.

How to create database in MongoDB

When you create new database in database server like MS SQL Server, you are used to using CREATE DATABASE command to create a new database and set its attributes etc. You will not find any command in MongoDB that is equivalent to this CREATE command. Then how do you create new database in MongoDB. In Mongo databases are more like logical contexts. So if you are using command line, when you issue use {dbname} command, then it is equivalent to creating a new database with that name and shell with switch its context to that database. That is all that you will be doing in MongoDB to create new database. If you are doing MongoDB development, then you are always calling GetDatabase method on MongoServer object. The simplest overloaded method takes name of the database as parameter. There are other overloaded method and one of those takes MongoDatabaseSettings object as paremeter. I will discuss more details about this in subsequent posts. For now we will let MongoDB use its default settings to create this logical database. Here is some sample code that shows this method in action.

private void ConnectToMongoServer(MongoClientSettings settings)
{
    try
    {
        var mongoDbClient = new MongoClient(settings);
        DatabaseServer = mongoDbClient.GetServer();
        DatabaseServer.Connect();
    }
    catch (MongoConnectionException ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }
}
public MongoDatabase GetDatabase(string dbName)
{
    return this.DatabaseServer.GetDatabase(dbName);
}

One important thing to know here is that when you issue use {dbname} command or call GetDatabase method, new database is not created right away if it does not already exists. MongoDB will wait till you insert any document (record) to create this database.

How to add new table in MongoDB

Coming from SQL world, you are looking for something that is equivalent to CREATE TABLE command. In MongoDB collections are equivalent to tables. If you think about it, table is nothing but a collection of records. So it makes sense to call it a collection. In MongoDB you are not restricted to defining schema of your table or collection before inserting any records. MongoDB uses dynamic schema. In more strict terms there is not schema for a collection of documents in a collection in MongoDB. Records in MongoDB are considered documents with certain attributes. These attributes are properties of your object. Following screenshot shows example of how Role objects looks like in Role collection that I have created in my database.

mongo documents

Here is what this class looks like in my application.

public class Role
{
  public ObjectId Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

As you can see MongoDB has created document in collection that exactly matches my class. When you insert first entry in your collection, MongoDB will automatically crate a new collection in database. This does not mean that only way to create a table or collection in MongoDB is by inserting a record. You can always call CreateCollection method on MongoDatabase object to create an empty table. Just mind it that when you can call CreateCollection method it creates just an empty collection and there is no schema or properties specified for documents or records that are going to be inserted in this collection. Following code shows how I created Roles collection by inserting new record in the table.

public void AddRole(Role role)
{
    try
    {
        var db = this.DatabaseConnector.GetDatabase("Commerce");
        var roles = db.GetCollection<Role>("Roles");
        roles.Insert(role);
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message);
        throw;
    }
}

As you can see from code snippet, for your C# code adding new record in MongoDB table is as simple as calling Insert method on MongoCollection object.

How to change schema of existing table in MongoDB

As I mentioned earlier, MongoDB uses dynamic schemas. The structure of the documents or records in a collection change as class or object for your records change. For example I added a new property, CreateDate to Role class.

public class Role
{
   public ObjectId Id { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public DateTime? CreateDate { get; set; }
}

When I called Insert method on Roles collection, it added a new document in the collection which has additional property CreateDate on it but existing records are not altered and do not have that new property.

mongo alter table

As you can see from screenshot, how records look like in the collection. This demonstrates true dynamic schema nature of the collection. A collection has records with different set of attributes.

In this post I talked about how to add and alter tables in MongoDB. In subsequent post(s) I will show how to perform some CRUD operations on records or document in table(s).

comments powered by Disqus

Blog Tags