Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava

Connect to MongoDB

In this guide, you can learn how to connect to a MongoDB instance or 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:

Connection String parts figure

This figure uses 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.

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.

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, 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, 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.

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.

←  Connection GuideConnection Options →