I am using latest Java Driver (2.11.1) for MongoDB. MongoDB Java API essentially is
1) When does a connection to db established? Is it when getDB() is called or getCollection() is called?
2) Is it better to call getDB() once or everytime you need? (does it matter? - MongoClient keeps DB object cached?)
3) Is it better to reuse single DBCollection object by multi threads or call getCollection() from multi-threads? (Is DBCollection cached?)
The MongoClient class manages a lazy loaded connection pool from your client application to a MongoDB cluster. You can initialize MongoClient with a specific number of connections per host as well as the number of threads which wait for a connection. Since MongoClient manages both the number of connections and thread concurrency, you'll want to use one instance of the class per virtual machine. Both of DB and DBCollection perform their operations though the MongoClient's connection pool, so there's no need to cache them for that reason. There's no limit to the number of DB or DBCollection objects you instantiate. However, since these classes are thread safe and can be set with specific read preferences & write concerns, you can use a single instance of DB or DBCollection class to perform multiple operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With