When does a MongoDB Java Driver application establish a connection?

I am using the latest Java driver (2.11.1) for MongoDB. MongoDB Java API Essentially

  • One instance of the MongoClient class (with internal connection pool)
  • getDB () to get the DB object
  • getCollection () to get the DBCollection object

1) When is the connection with db established? Is this when getDB () is called or getCollection () is called?

2) Is it better to call getDB () once or every time you need to? (does it matter? - Does MongoClient store the DB object in the cache?)

3) Is it better to reuse a single DBCollection object with multiple threads or call getCollection () from multiple threads? (Is DBCollection caching?)

+6
source share
2 answers

The MongoClient class manages the lazy loaded connection pool from your client application to the MongoDB cluster. You can initialize MongoClient with a certain number of connections per host, as well as the number of threads waiting for connections. Since MongoClient controls both the number of connections and the concurrency stream, you will want to use one instance of the class for each virtual machine. Both DB and DBCollection perform their operations, although the connection pool is MongoClient, so there is no need to cache them for this reason. There is no limit to the number of DB or DBCollection objects you create. However, since these classes are thread safe and can be installed with specific read preferences and write problems, you can use a single instance of the DB class or DBCollection to perform several operations.

+7
source

1) the connection is established when we perform some operation (find, update, delete, etc.)

2) Doc says: "Usually you only create one instance for a given database cluster and use it in your application." Thus, it makes no sense to cache the DB object, and it is also not cached in the driver code

3) DBCollection and DB are thread safe. DBCollection is cached in the DBApiLayer class in the driver.

0
source

Source: https://habr.com/ru/post/946644/


All Articles