Question

I don't have any prior experience with database, but I have to use it for a app that I'm building, and I choose MongoDB.

Now everything is working, but I'm creating a new Mongo object every time I have to make an request to the database, and I understand that's wrong.

So I want ask and learn what is the correct way to do this, I have some code like the following in a class called MongoDbConnnection:

public class MongoDbConnection {
    private static Mongo _mongo;
        public static Mongo getMongo()
        {
            if (_mongo == null) {
            try {
                    _mongo = new Mongo();
                } catch (UnknownHostException e) {
                    _mongo = null;
                    e.printStackTrace();
                } catch (MongoException e) {
                    _mongo = null;
                    e.printStackTrace();
                }
            }
        return _mongo;
    }
}

So that every time I need to do a query, I do Mongo m = MongoDbConnnection.getMongo(); and proceed forward.

Is this correct?

I also confuse about when to close the connection, as I have another class that extends HttpServlet and will respond GET, every time someone request that url I will have to query the database and return the information. If I close right after I respond to one request, what if other people request it again right after that. Then I have to create a new Mongo object again?

In other words, I know Mongo instance maintain a connection poll, so when I call m.close(), am I just replace the connection I used, or am I setting object m to null?

Was it helpful?

Solution

Yes, you are mostly getting a connection from the pool of connection maintained for you with:

Mongo m = new Mongo();
DB db = m.getDB( "mydb" );

You only need one Mongo object, and it is thread safe.

I have not looked into the implementation in details, but you have to call

db.close() from your code. 

This will simply returns the connection to the pool and not close it. If you forget to do it, I suppose it is going to take time, before the Mongo object realize the connection is not used anymore.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top