Docs Menu

Connection Guide

On this page

  • Overview
  • MongoClient
  • Connection URI
  • Other Ways to Connect to MongoDB
  • Connect to a MongoDB Server on Your Local Machine
  • Connect to a Replica Set
  • Compression
  • Enable Compression
  • Compression Algorithm Dependencies
  • Connection Options

In this guide, you can learn how to connect to a MongoDB instance or replica set deployment using the MongoDB Java driver.

For information about authenticating with a MongoDB instance, see Authentication. To learn more about using the driver with the Java Naming and Directory Interface (JNDI), see JNDI. To configure TLS/SSL security for connections to your MongoDB instance, see TLS/SSL.

Use the MongoClients.create() method to construct a MongoClient. As each MongoClient represents a threadsafe pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple threads. All resource usage limits, such as max connections, apply to individual MongoClient instances.


Always call MongoClient.close() to clean up resources when an instance is no longer needed.

The connection URI provides a set of instructions that the driver uses to connect to a MongoDB deployment. It instructs the driver on how it should connect to MongoDB and how it should behave while connected. The following example explains each part of a sample connection URI:

Connection String parts figure

In this example, we use the Standard Connection String Format, mongodb for the protocol. You can also use the DNS Seed List Connection Format, mongodb+srv, if you want more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients.


If your deployment is on MongoDB Atlas, see the Atlas driver connection guide and select Java from the language dropdown to retrieve your connection string.

The next part of the connection URI contains your credentials if you are using a password-based authentication mechanism. Replace the value of user with your username and pass with your password. If your authentication mechanism does not require credentials, omit this part of the connection URI.

The next part of the connection URI specifies the hostname or IP address, followed by the port of your MongoDB instance. In the example, we use as the hostname and 27017 as the port. Replace these values to refer to your MongoDB instance.

The last part of the connection URI contains connection options as parameters. In the example, we set two connection options: maxPoolSize=20 and w=majority. For more information on connection options, skip to the Connection Options section of this guide.

The following code shows how you can use the sample connection URI in a client to connect to MongoDB.

package fundamentals;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class RunCommand {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "mongodb://";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("admin");
try {
Bson command = new BsonDocument("ping", new BsonInt64(1));
Document commandResult = database.runCommand(command);
System.out.println("Connected successfully to server.");
} catch (MongoException me) {
System.err.println("An error occurred while attempting to run a command: " + me);

If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:

  1. Download the Community or Enterprise version of MongoDB Server.
  2. Install and configure MongoDB Server.
  3. Start the server.

Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.

After you successfully start your MongoDB server, specify your connection string in your driver connection code.

If your MongoDB Server is running locally, you can use the connection string "mongodb://localhost:<port>" where <port> is the port number you configured your server to listen for incoming connections.

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.

A MongoDB replica set deployment is a group of connected instances that store the same set of data. This configuration of instances provides data redundancy and high data availability.

To connect to a replica set deployment, specify the hostname (or IP address) and port numbers of one or more members of the replica set separated by commas. By default, specifying the hostname and port number of a single MongoDB instance only connects to the specified member of the replica set. However, you can automatically discover and connect to all members of the replica set in several different ways. To create a replica set connection:

  • specify the name of the replica set using the replicaSet parameter
  • specify the directConnection parameter with a value of false
  • specify multiple hosts, instead of a single host

Each of these methods causes the driver to discover any unspecified hosts in the replica set.

The following connection string specifies three hosts in the cluster and replica set named "myRs".


The following examples show how to specify multiple hosts to a MongoClient instance using either the ConnectionString or MongoClientSettings class. Select the tab corresponding to the code snippet you would like to see:


Although it is possible to connect to a replica set deployment by providing only a single host, you should provide the driver with the full list to ensure that it is able to connect even if one host fails.


The replicaSet option is not necessary to connect to a replica set, since the driver automatically detects and handles multiple hosts in the connection string as a replica set.

You can compress messages passing between your MongoDB instance and the driver. MongoDB drivers support up to three different algorithms depending on release version:

  1. Snappy: available in MongoDB 3.4 and later.
  2. Zlib: available in MongoDB 3.6 and later.
  3. Zstandard: available in MongoDB 4.2 and later.

You can specify one or more compression algorithms, but the driver uses the first compressor in the list supported by the connected MongoDB instance.


Applications that require Snappy or Zstandard compression must add explicit dependencies for those algorithms.

You can enable compression for the connection to your MongoDB instance in two different ways: through a parameter in your connection string, or using a method in the MongoClientSettings.Builder class.

The JDK supports Zlib compression natively, but Snappy and Zstandard depend upon open source implementations. See snappy-java and zstd-java for details.

This section explains MongoDB connection and authentication options supported by the driver. You can pass the connection options as parameters of the connection URI to specify the behavior of the client.

Option Name
Specifies the maximum size of the connection pool.
Specifies the maximum amount of time, in milliseconds, that a thread may wait for a connection to become available.
Specifies the maximum amount of time, in milliseconds, the driver will wait for server selection to succeed before throwing an exception.
When communicating with multiple instances of MongoDB in a replica set, the driver will only send requests to a server whose response time is less than or equal to the server with the fastest response time plus the local threshold, in milliseconds.
Specifies the frequency, in milliseconds, that the driver will wait between attempts to determine the current state of each server in the cluster.
Specifies that the connection string provided includes multiple hosts. When specified, the driver attempts to find all members of that set.
Specifies that all communication with MongoDB instances should use TLS/SSL. Superseded by the tls option.
Specifies that all communication with MongoDB instances should use TLS. Supersedes the ssl option.
Specifies that the driver should allow invalid hostnames for TLS connections. Has the same effect as setting tlsAllowInvalidHostnames to true. To configure TLS security constraints in other ways, use a custom SSLContext.
Specifies that the driver should allow invalid hostnames in the certificate for TLS connections. Supersedes sslInvalidHostNameAllowed.
Specifies the maximum amount of time, in milliseconds, the Java driver will wait for a connection to open before timing out.
Specifies the maximum amount of time, in milliseconds, the Java driver will wait to send or receive a request before timing out.
Specifies the maximum amount of time, in milliseconds, the Java driver will allow a pooled connection to idle before closing the connection.
Specifies the maximum amount of time, in milliseconds, the Java driver will continue to use a pooled connection before closing the connection.
Specifies that the driver must wait for the connected MongoDB instance to group commit to the journal file on disk for all writes.
string or integer
Specifies the write concern. For more information on values, see the server documentation for the w option.
Specifies a time limit, in milliseconds, for the write concern. For more information, see the server documentation for the wtimeoutMS option.
Specifies the read preference. For more information on values, see the server documentation for the readPreference option.
Specifies the read preference tags. For more information on values, see the server documentation for the readPreferenceTags option.
Specifies, in seconds, how stale a secondary can be before the driver stops communicating with that secondary. Not providing a parameter or explicitly setting it to -1 indicates that there should be no staleness check for secondaries. The minimum value is either 90 seconds or the heartbeat frequency plus 10 seconds, whichever is greater. For more information, see the server documentation for the maxStalenessSeconds option.
Specifies the authentication mechanism that the driver should use if a credential was supplied. By default, the client picks the most secure mechanism available based on the server version. For possible values, see the server documentation for the authMechanism option.
Specifies the database that the supplied credentials should be validated against. Defaults to admin.
Specifies authentication properties for the specified authentication mechanism as a list of colon-separated properties and values. For more information, see the server documentation for the authMechanismProperties option.
Specifies the name of the application provided to MongoDB instances during the connection handshake. Can be used for server logs and profiling.
Specifies one or more compression algorithms that the driver will attempt to use to compress requests sent to the connected MongoDB instance. Possible values include: zlib, snappy, and zstd.
Specifies the degree of compression that Zlib should employ to decrease the size of requests to the connected MongoDB instance. The level can range from -1 to 9, with lower values compressing faster (but resulting in larger requests) and larger values compressing slower (but resulting in smaller requests).
Specifies that the driver must retry supported write operations if they fail due to a network error. Defaults to true.
Specifies that the driver must retry supported read operations if they fail due to a network error. Defaults to true.
Specifies the UUID representation to use for read and write operations. For more information, see the the driver documentation for the MongoClientSettings.getUuidRepresentation() method.
Specifies that the driver must connect to the host directly.

For a complete list of options, see the ConnectionString API reference page.

Give Feedback
© 2021 MongoDB, Inc.


  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.