views:

57

answers:

2

I'm approaching MongoDB from an NHibernate background and I want to know what the best practices are for efficient usage in a web context.

With NHibernate, I create a single ISessionFactory for the life of the application, then use an instance of an ISession per request. Take the below code for example (which i hope is typical, please correct if its not ideal).

Would I typically have a single instance of the Mongo class per application, or per request? What about var db? Or do I do use all the code below whenever I want DB interaction?

Update: I'm using mongodb-csharp (although please suggest a better alternative if it exists)

Thanks

using (var mongo = new Mongo())
{
    mongo.Connect();

    var db = mongo.GetDatabase("mydb");

    var mongoCollection = db.GetCollection("mycollection");

    var document = new Document(Guid.NewGuid().ToString(), new
                                                    {
                                                        x = 1,
                                                        y = 2
                                                    });

    mongoCollection.Insert(document);
}
A: 

Each of the drivers typically have some form of persistent connection or connection pooling. I'm not sure which language / driver you're using, but check your docs for connection pooling.

Also, when running Mongo.connect() you'll typically have connection string (mongodb://user:pwd@host:port/db), which will cut down on the lines of code and get you straight to the collection.

Also, you generally don't need to use GUID. Mongo drivers generally provide some form of "MongoID" which is specific to Mongo. In addition, the default behaviour is to create an ID for you if you don't have one.

Other than that, I would look at your driver / library in detail as they are slightly different.

Gates VP