Wednesday, 7 December 2011

Tomcat and MongoDB

When I started with MongoDB I wanted to use it with everybody's old favourite application server, Tomcat.
There is no point reinventing the wheel so I hunted for usage examples.  I struggled to find any best practice implementation, so I decided to hack my own together.

A requirement I had was I had was I wanted to be able to deploy the web app to a range of different environments, so I needed the service to be flexible.  The simplest way I could think of was pulling the config from the application's web.xml file.

The Mongo object instance represents a pool of connections to the database so you will only need one object of class Mongo even with multiple threads.

web.xml snippet:

MongoService snippet:

Then from the data access object you can specify and authenticate to the relevant DB.

XxxDAO snippet:

This has been working like a dream for me proving to be an extremely convenient way to easily connect to Mongo.


  1. This is a comment received via a site other than this blog.

    Comment from X:
    Depending on your needs you may want to look at using a Mongo connection string. This can simplify your configuration code even more.

    Response to X:

    Yes, X. You are quite correct; would indeed result in much less code.

    The reason why I opted to implement it this way was the connection string can become unreadable (or more difficult to read at least) when you add further hosts to the set and start to use more of the connection string options. For me it was easier and quicker to write a unit test to validate the configuration parser rather than the entire connection string.

    For instance, reading a host string from the config meant writing a regex to verify it was a valid host string; simple. Then similarly validating the port to verify it was a numeric in the appropriate range was simple, it goes on... I could then piece all the sub-elements together. Whereas, if I'm pulling an entire connection string, even for a relatively simple mongodb set up, then the task of verifying the connection string was much more daunting.

  2. Both Tomcat and Mongo run on the same machine. There are no settings for this configuration. Now I need my Tomcat to connect to an other Mongo (on the other machine). How can I do it?
    For more information please visit here mongodb hosting godaddy