Docs Menu
Docs Home
/ / /
Java Sync Driver
/ /

Connect to MongoDB

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

You can view sample code to connect to an Atlas cluster or continue reading to learn more about the MongoClient class and connection URIs.

You can connect to and communicate with MongoDB using the MongoClient class.

Use the MongoClients.create() method to construct a MongoClient.

Important

Reuse Your Client

As each MongoClient represents a thread-safe pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple threads. To learn more about how connection pools work in the driver, see the FAQ page.

All resource usage limits, such as max connections, apply to individual MongoClient instances.

To learn about the different settings you can use to control the behavior of your MongoClient, see the guide on MongoClient Settings.

Tip

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 figure explains each part of a sample connection URI:

An example of a connection string that demonstrates the protocol, credentials, hostname or IP, port, and connection options

In this example, you connect to an Atlas MongoDB deployment that has a DNS SRV record. For more details, see the DNS Seed List Connection Format documentation. This format offers flexibility in deployment and the ability to change the servers in rotation without reconfiguring clients.

Note

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.

If you are connecting to an instance or replica set that does not have a DNS SRV address, you must use mongodb for the protocol, which specifies the Standard Connection String Format.

After the protocol, the connection string 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, sample.host represents the hostname and 27017 is the port number. Replace these values to refer to your MongoDB instance.

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

To connect to a MongoDB deployment on Atlas, create a client. You can create a client that uses your connection string and other client options by passing a MongoClientSettings object to the MongoClients.create() method.

To instantiate a MongoClientSettings object, use the builder method to specify your connection string and any other client options, and then call the build() method. Chain the applyConnectionString() method to the builder to specify your connection URI.

You can set the Stable API version client option to avoid breaking changes when you upgrade to a new version of MongoDB Server. To learn more about the Stable API feature, see the Stable API page.

The following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:

package fundamentals;
import com.mongodb.*;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class MongoClientConnectionExample {
public static void main(String[] args) {
// Replace the placeholder with your Atlas connection string
String uri = "<connection string>";
// Construct a ServerApi instance using the ServerApi.builder() method
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
// Create a new client and connect to the server
try (MongoClient mongoClient = MongoClients.create(settings)) {
MongoDatabase database = mongoClient.getDatabase("admin");
try {
// Send a ping to confirm a successful connection
Bson command = new BsonDocument("ping", new BsonInt64(1));
Document commandResult = database.runCommand(command);
System.out.println("Pinged your deployment. You successfully connected to MongoDB!");
} catch (MongoException me) {
System.err.println(me);
}
}
}
}

If you are connecting to a single MongoDB deployment 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 deployment 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 deployment.

Important

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

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

If your MongoDB deployment 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 deployment, 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 hostnames (or IP addresses) and port numbers of the members of the replica set.

If you are not able to provide a full list of hosts in the replica set, you can specify a single or subset of the hosts in the replica and instruct the driver to perform automatic discovery in one of the following ways:

  • Specify the name of the replica set as the value of the replicaSet parameter

  • Specify false as the value of the directConnection parameter

  • Specify more than one host in the replica set

Tip

Although you can specify a subset of the hosts in a replica set, include all the hosts in the replica set to ensure the driver is able to establish the connection if one of the hosts are unreachable.

The following examples show how to specify multiple hosts to a MongoClient instance using either the ConnectionString or MongoClientSettings class. Select the tab that corresponds to your preferred class.

ConnectionString connectionString = new ConnectionString("mongodb://host1:27017,host2:27017,host3:27017/");
MongoClient mongoClient = MongoClients.create(connectionString);
ServerAddress seed1 = new ServerAddress("host1", 27017);
ServerAddress seed2 = new ServerAddress("host2", 27017);
ServerAddress seed3 = new ServerAddress("host3", 27017);
MongoClientSettings settings = MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(seed1, seed2, seed3)))
.build();
MongoClient mongoClient = MongoClients.create(settings);

Back

Connection Guide

Next

Connection Options