Docs Menu

Docs HomeJava

FAQ

On this page

There are two types of MongoClient because we wanted a cleaner API for new users that didn't have the confusion of including multiple CRUD APIs. We wanted to ensure that the new CRUD API was available in a Java package structure that would work well with Java module support introduced in Java 9.

New applications should generally use the com.mongodb.client.MongoClient interface, which supports:

  • Configuration with MongoClientSettings and ConnectionString. You can create instances of this interface via factory methods defined in the com.mongodb.client.MongoClients class.

  • CRUD API using MongoDatabase, and from there, MongoCollection

You should use the com.mongodb.MongoClient class if you require support for the legacy API, which supports:

  • Configuration with MongoClientOptions and MongoClientURI

  • CRUD API using DB, and from there, DBCollection. You can access this API via the getDB() method.

For applications that require a mix of the new and legacy APIs, com.mongodb.MongoClient also supports:

  • Configuration with MongoClientSettings and ConnectionString, the only difference being that you create instances via constructors instead of a factory class.

  • CRUD API using MongoDatabase, and from there, MongoCollection. You can access this API via the getDatabase() method.

You can use the MongoClientSettings class to specify configurations for MongoClient instances. To construct MongoClientSettings instances, use the MongoClientSettings.Builder class.

Here are the sections of our documentation that show how to perform different tasks with the MongoClientSettings class:

For more information on the MongoClientSettings class, see the API Documentation for MongoClientSettings.

This is a known error that can occur when using the TLS 1.3 protocol with specific versions of the JDK. If you encounter this error when connecting to your MongoDB instance or cluster, update your JDK to one of the following patch versions or newer:

  • JDK 11.0.7

  • JDK 13.0.3

  • JDK 14.0.2

Every MongoClient instance has a built-in connection pool for each server in your MongoDB topology. Connection pools open sockets on demand to support concurrent MongoDB operations in your multithreaded application.

The maximum size of each connection pool is set by the maxPoolSize option, which defaults to 100. If the number of in-use connections to a server reaches the value of maxPoolSize, the next request to that server will wait until a connection becomes available.

Each MongoClient instance opens two additional sockets per server in your MongoDB topology for monitoring the server's state.

For example, a client connected to a 3-node replica set opens 6 monitoring sockets. It also opens as many sockets as needed to support an application's threads on each server, up to the value of maxPoolSize. If maxPoolSize is 100 and the application only uses the primary (the default), then only the primary connection pool grows and there can be at most 106 total connections. If the application uses a read preference to query the secondary nodes, their pools also grow and there can be 306 total connections.

Additionally, connection pools are rate-limited such that each connection pool can only create, at maximum, the value of maxConnecting connections in parallel at any time. Any additional thread stops waiting in the following cases:

  • One of the existing threads finishes creating a connection, or an existing connection is checked back into the pool.

  • The driver's ability to reuse existing connections improves due to rate-limits on connection creation.

You can set the minimum number of concurrent connections to each server with the minPoolSize option, which defaults to 0. The connection pool will be initialized with this number of sockets. If sockets are closed due to any network errors, causing the total number of sockets (both in use and idle) to drop below the minimum, more sockets are opened until the minimum is reached.

You can set the maximum number of milliseconds that a connection can remain idle in the pool before being removed and replaced with the maxIdleTimeMS option, which defaults to 0 (no limit).

The following default configuration for a MongoClient works for most applications:

MongoClient client = new MongoClient("<connection string>")

Create a client once for each process, and reuse it for all operations. It is a common mistake to create a new client for each request, which is very inefficient.

To support high numbers of concurrent MongoDB operations within one process, you can increase maxPoolSize. Once the pool reaches its maximum size, additional threads wait for sockets to become available.

The driver does not limit the number of threads that can wait for sockets to become available and it is the application's responsibility to limit the size of its pool to bound queuing during a load spike. Threads wait for the amount of time specified in the waitQueueTimeoutMS option, which defaults to 120000, or 120 seconds.

A thread that waits more than the length of time defined by waitQueueTimeoutMS for a socket raises a connection error. Use this option if it is more important to bound the duration of operations during a load spike than it is to complete every operation.

When MongoClient.close() is called by any thread, the driver closes all idle sockets and closes all sockets that are in use as they are returned to the pool.

No, the PojoCodecProvider automatically generates an ObjectId.

Yes. For an example of this, see our implementation

Yes, by using a discriminator.

A discriminator is a property that identifies a specific document schema. You can use it for inheritance and storing multiple types of documents within the same collection or parent document (if you embed subdocuments).

For example, if you have an Event class that you extend in Java (e.g. MachineEvent or NetworkEvent), using a discriminator identifies which class the PojoCodecProvider should use to serialize/deserialize the document.

For more information, see our POJO Customization guide.

Yes, the 3.7 Java driver adds native support for JSR-310 Instant, LocalDate & LocalDateTime.

Yes, you can build your own codec for this class and add it to the registry.

Add the codec to the first in the list of providers, before the default codec registry and before the PojoCodecProvider:

CodecRegistry registry = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(
new MyDateAsStringCodec()),
MongoClientSettings.getDefaultCodecRegistry(),
fromProviders(pojoCodecProvider));

You can configure the PojoCodecProvider to use the SET_PRIVATE_FIELDS_CONVENTION, which sets a private field through reflection if no public setter is available.

No. The native POJO codec assumes that getters/setters have the same modifiers for each field.

For example, the following methods throws an exception during encoding:

private String getField();
public String setField(String x);

This exception means you need to register a codec for the class since there is none at the moment.

There is no annotation. We recommend adding a static string in your class as shown:

public class Person {
public static final String COLLECTION_NAME = "people";
}

The following snippet specifies the collection name for a particular POJO class:

database.getCollection(Person.COLLECTION_NAME, Person.class);

The following example shows how to connect to a MongoDB instance with the legacy API and the current API.

Imagine we are connecting to a collection that contains only this document:

{"_id": 1, "val": 1}

The output of the preceding code snippet should look like this:

{"_id": 1, "val": 1}

For more information on the legacy classes and methods used in the preceding example, see the following API documentation pages:

See the Migrate from the Legacy API page for a list of differences between the legacy and current API.

Here is an example showing how to use the legacy MongoClientOptions and MongoClientURI classes to set your write concern:

For more information on the legacy classes and methods used in the preceding example, see the following API Documentation pages:

See the Migrate from the Legacy API page for a list of differences between the legacy and current API.

If you are unable to find the answer to your question here, try our forums and support channels listed in the Issues and Help section.

←  API DocumentationIssues & Help →
Share Feedback
© 2023 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2023 MongoDB, Inc.