30

I'm holding one instance of MongoClient and DB in my application, and every time that I want to execute some operation I call getCollection().
I'm wondering if I need to explicitly close the connection, just like connection.close() in JDBC.

To emphasize, I have only one MongoClient instance. My question is not about closing MongoClient but closing the connections I believe it opens when I'm calling getCollection().

danieln
  • 4,795
  • 10
  • 42
  • 64

2 Answers2

35

No, you do not need to close connections to DB - your only connection is via MongoClient and as the documentation states - it handles connection pooling for you.

The only resource that you would want to clean up would be a cursor which you should close() when you're done with it.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
8

You should close if you have many MongoClient.

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

MongoClient.close() to clean up resources

MongoClient.close() - closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used.

More: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

MariuszS
  • 30,646
  • 12
  • 114
  • 155
  • Of course if you have many instances without having many MongoDB instances in your app then that is bad programming – Sammaye Nov 12 '13 at 20:55
  • 2
    I have only one MongoClient instance. My question is not about closing MongoClient but closing the connections I believe it opens when I'm calling getCollection. – danieln Nov 13 '13 at 07:15