Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managing MongoDB object lifetime in a web app

I've got a RESTful backend using mongodb as an underlying storage. I'm using c# driver. Documentation states that mongo manages its connection pool by itself.

The question is: to communicate with mongodb I need the instances of the following implementations

  • IMongoClient
  • IMongoDatabase
  • IMongoCollection<T>

What are the best practices to manage lifetime of these objects? I can store them with singleton lifestyle per server (appdomain) or I can keep creating them per request. For now only IMongoCollection<T> is per request.

like image 413
Cortlendt Avatar asked Apr 14 '15 09:04

Cortlendt


Video Answer


1 Answers

The recommended way is to hold a single MongoClient instance and use it to get your databases and collections when you need them.

You may aggressively cache all these instances if it's critical for your performance however in most cases that's unnecessary as all these types are very simple and cheap to create. For example this is the GetCollection method:

public override IMongoCollection<TDocument> GetCollection<TDocument>(string name, MongoCollectionSettings settings)
{
    Ensure.IsNotNullOrEmpty(name, "name");

    settings = settings == null ?
        new MongoCollectionSettings() :
        settings.Clone();

    settings.ApplyDefaultValues(_settings);

    return new MongoCollectionImpl<TDocument>(this, new CollectionNamespace(_databaseNamespace, name), settings, _cluster, _operationExecutor);
}

Other than some argument handling and a couple of allocations there's really nothing being done here. What's actually expensive is the connection pooling and (as you mentioned) it's handled by the driver internally.

like image 98
i3arnon Avatar answered Oct 12 '22 03:10

i3arnon