0

I have a web application in JSP with MongoDB and it performs different operations like search, update, delete on multiple pages. So can I create a single MongoClient instance for all pages or create single instance and call them whenever necessary? which is more efficient with respect to efficiency and speed?

2 Answers 2

2

In the official document in http://mongodb.github.io/mongo-java-driver/3.2/driver/getting-started/quick-tour/

It is said that:

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.

And it is important to note that:

Typically you only create one MongoClient instance for a given database cluster and use it across your application. When creating multiple instances:

  • All resource usage limits (max connections, etc) apply per MongoClient instance

  • To dispose of an instance, make sure you call MongoClient.close() to clean up resources

Hope, it helps!

Sign up to request clarification or add additional context in comments.

Comments

1

MongoClient is a Connection Pool object. You should create it only once and use it across application.

From the API Doc

A MongoDB client with internal connection pooling. For most applications, you should have one MongoClient instance for the entire JVM.

If you need to change the pool size use MongoClientOptions.Builder

MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
MongoClientOptions options = builder.connectionsPerHost(30).build();
MongoClient client = new MongoClient(new ServerAddress("localhost"), options);

Generally number of pages has nothing to do with the number of connections that we create.

Our server load determines how many connections we should be using. In production environment we always use a Connection Pool. Connection Pool is a storage for already instantiated clients, which manages the life cycle of these clients (instantiation and disposing). Client object is obtained using this pool object. Size of pool depends on the load on the server. Load here means number of database calls made by the application in production environment per unit time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.