I am using the following code based on some tutorials to connect to the mongo database.
I have some doubts regarding the design:
I am new to mongodb so my question may sound a bit naive.
public class MongoConnection {
private static MongoClient mongoClient = null;
private static String IP = "mongodb://user:pwd@localhost:27017/?authSource=demodb&authMechanism=SCRAM-SHA-1";
private static String DATABASE = "demodb";
static {
mongoClient = new MongoClient(new MongoClientURI(IP));
}
private MongoConnection() {
}
public static DB getDB() {
return mongoClient.getDB(DATABASE);
}
}
From the docs:
The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.
And from the previous versions' quick start guides:
The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application.`
So, MongoClient.getDb(..) should not have any problem among threads
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