Search code examples
c#asp.netasp.net-mvcmongodbmongodb-.net-driver

mongodb connection pooling in MVC


My application is based on asp.net (MVC) and mongodb.

I'm tracking each client request and write it in into my mongodb database.

Currently, each client request is open new DB connection.

This is my code:

public class MyController
{
    public ActionResult MyOperation(string input)
    {
        const string connectionString = "mongodb://URL";
        var client = new MongoClient(connectionString);
        var server = client.GetServer();
        var database = server.GetDatabase("dbname");
        var collection = database.GetCollection<ElcoRequest>("MyCollection");
        // Create new row
    }
}

I'm want to use same DB-Connection(s) for all the request. (Instead of my current solution that open new connection for each DB)

I know that when working with ADO.NET, there are something that called "Connection pooling". What is the equivalent in mongodb?


Solution

  • Connection pooling is handled internally in the MongoClient class. You don't need to implement pooling yourself.

    As long as you're using the same connection string and settings you can create new MongoClient instance as you are doing now.

    MongoDB MongoClient documentation:

    The connections to the server are handled automatically behind the scenes (a connection pool is used to increase efficiency).