Reputation: 114
As mentioned in the docs: http://mongodb.github.io/mongo-java-driver/3.3/driver/getting-started/quick-tour/
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.
Using codes below can get the collection(just like 'table' in the RDMS):
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("test");
I found these code always return new instances, so,how about making the MongoDatabase or MongoCollection as the Singleton in my applicaiton?
Upvotes: 4
Views: 3002
Reputation: 3191
MongoClient should typically be the singleton. Your quote mentions this
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.
It also mentions this in the javadocs:
A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.
It does not make sense to have MongoDatabase or MongoCollection as singletons mainly (there are other reasons) because the underlying connection can get stale, which requires some coding to refresh a singleton MongoDatabase or singleton MongoCollection.
Upvotes: 6