Connecting to MongoDB database using .Net in MVC application

Download sample MongoDB connection code

In previous posts Installing MongoDB for MVC applications and Configuring MongoDB as Windows Service for MVC applications, I discussed the very first steps you have to perform to get your environment set up for MongoDB use in your MVC application. In this post I will show how to get started with writing some very basic .Net code to establish connection with MongoDB.

Download C# driver for MongoDB

Like every other database, you will need some library that acts as an interface between database and your code. For example when you have to connect to Microsoft SQL server, you are using System.Data.SqlClient namespace to use objects that allows you to connect to database and perform all the actions. Similarly you will need some implementation that allows you to write high level code to perform the same actions. If you look at MongoDB documentation, this connecting glue is called Connector. MongoDB provides official C# driver for it. You can download it from here. The easiest way to do, as mentioned in documentation as well, is to use NuGet package to add reference to these libraries in your project.

mongo nuget package

Once you have installed this NuGet package, you will see the following assemblies added to references of your project. This is all that you will need to set up your project to start using MongoDB connector. MongoDB team has provided good documentation on getting started with this connector. You can read on it here. In this post I will highlight on some of the topics that need some more description.

mongodb connector assemblies

As described in documentation of the connector, you will need to add using statements for namespaces for MongoDB connector. You can skip this part if you plan on typing fully qualified name of each object. Like any other objects, you would want to type minimum possible code to increase productivity. Following are very basic namespaces that you will need.

  • using MongoDB.Driver;
  • using MongoDB.Bson;

Connection string for MongoDB

The very first step in using database is going to be connecting to that database using a connection string. MongoDB has detailed instructions on format of the connection string here. In its simplest form, the connection string looks like below.

mongodb://localhost:27017

This connection string has two important parts. Server address and port on which MongoDB is listening. In my example I have MongoDB running on my local machine, so I have server name set to localhost. You will replace this value with actual server(s) where MongoDB is running. Second part is port number. If you have default installation of MongoDB, then it is listening on port 27017. In that case you can ignore specifying port number. The connector has default value of port number as 27017 set in it. But if your installation of MongoDB is listening on some other port, then it is very important that you specify that port number after :. If you do not specify correct port, then you will get an exception. Later on I will show you how that exception gets raised and what does it look like. In my case I have my connection string looking like below.

mongodb://localhost:29001

Following is prototype code that shows how to establish connection with MongoDB database.

private const string ConnectionString = "mongodb://localhost";
private static void ConnectToMongoServer()
{
    try
    {
        var mongoDbClient = new MongoClient(ConnectionString);
        _myMongoServer = mongoDbClient.GetServer();
        _myMongoServer.Connect();
    }
    catch (MongoConnectionException ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }
}

If you notice, I did not specify port number in this connection string. When I ran this code, I got MongoConnectionException

Unable to connect to server localhost:27017: Object reference not set to an instance of an object..

As you can see that first part of the message is very clear that there is issue connecting on default port 27017. As I mentioned earlier that I did not install my MongoDB to listen on default 27017 port. My installation is listening on 29001. To fix this exception, I had to change connection string to mongodb://localhost:29001.

More control on MongoDB connection string

MongoDB connector provides alternate means to specify database connection details as well. Server address and port number are not the only two parameters that you can specify for your control. MongoDB connection string lets you specify all the control parameters to customize settings. To facilitate MongoDB connector exposes an overloaded constructor for MongoClient object. This constructor takes MongoClientSettings as parameter. In MongoClientSettings you can set individual connection settings. Following code shows alternate way of establishing connection to MongoDB.

private const string DatabaseHost = "localhost";
private const int DatabasePort = 29001;
private static MongoClientSettings GetMongoConnectionSettings()
{
    var dbAddress = new MongoServerAddress(DatabaseHost, DatabasePort);
    var settings = new MongoClientSettings() { Server = dbAddress, ConnectTimeout = TimeSpan.FromSeconds(45) };
    return settings;
}
private static void ConnectToMongoServer(MongoClientSettings settings)
{
    try
    {
        var mongoDbClient = new MongoClient(settings);
        _myMongoServer = mongoDbClient.GetServer();
        _myMongoServer.Connect();
    }
    catch (MongoConnectionException ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }
}

You can see from this code snippet that I have used another object MongoServerAddress to specify database server address and port.

This is how you establish connection to MongoDB database. There is one thing I would like to point out in this code. I have called Connect method on MongoClient object to open connection. This is just for illustration purpose. In production code, you do not have to call Connect and Disconnect. Here are some notes from official documentation.

The C# driver has a connection pool to use connections to the server efficiently. There is no need to call Connect or Disconnect; just let the driver take care of the connections (calling Connect is harmless, but calling Disconnect is bad because it closes all the connections in the connection pool).

If you are looking into checking if your database is up and running then calling Connect method will let you know if your connection string is valid and if your database installation is listening for connections.

This post discussed the very basic step of connecting to MongoDB database. I have attached the prototype code from my application with this post. In next post(s), I will discuss some more implementations to perform basic tasks in MongoDB using .Net driver.

comments powered by Disqus

Search

Social

Weather

20.3 °C / 68.5 °F

weather conditions Clouds

Monthly Posts

Blog Tags