.NET best practices for MongoDB connections? .NET best practices for MongoDB connections? mongodb mongodb

.NET best practices for MongoDB connections?


Most answers here are outdated and are no longer applicable as the .net driver has matured and had numberless features added.

Looking at the documentation of the new 2.0 driver found here:http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/connecting/

The .net driver is now thread safe and handles connection pooling. According to documentation

It is recommended to store a MongoClient instance in a global place, either as a static variable or in an IoC container with a singleton lifetime.


The thing to remember about a static connection is that it's shared among all your threads. What you want is one connection per thread.


When using mongodb-csharp you treat it like you would an ADO connection.When you create a Mongo object it borrows a connection from the pool, which it owns until it is disposed. So after the using block the connection is back into the pool.Creating Mongo objects are cheap and fast.

Example

for(var i=0;i<100;i++) {         using(var mongo1 = new Mongo())         using(var mongo2 = new Mongo())         {                 mongo1.Connect();                 mongo2.Connect();         } } 

Database Log
Wed Jun 02 20:54:21 connection accepted from 127.0.0.1:58214 #1
Wed Jun 02 20:54:21 connection accepted from 127.0.0.1:58215 #2
Wed Jun 02 20:54:21 MessagingPort recv() errno:0 No error 127.0.0.1:58214
Wed Jun 02 20:54:21 end connection 127.0.0.1:58214
Wed Jun 02 20:54:21 MessagingPort recv() errno:0 No error 127.0.0.1:58215
Wed Jun 02 20:54:21 end connection 127.0.0.1:58215

Notice it only opened 2 connections.

I put this together using mongodb-csharp forum.http://groups.google.com/group/mongodb-csharp/browse_thread/thread/867fa78d726b1d4