Docs Menu

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. 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 information, see the DNS Service Discovery section of this guide.

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 use DNS service discovery to look up the DNS SRV record of the service you're connecting to, specify the SRV connection format in your connection string. If you specify this format, the Java driver automatically rescans for new hosts. Your deployment can add hosts to its topology without requiring changes in your client configuration.

The following code shows a connection string that uses the SRV connection format:

String uri = "mongodb+srv://<hostname>/";

To learn more about the SRV connection format, see the SRV Connection Format entry in the MongoDB Server manual.

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);

This section answers questions that may arise when connecting to MongoDB.

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 Frequently AsAPIs. 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 generally use the com.mongodb.client.MongoClient interface, which supports the following features:

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

  • Access to the CRUD API by using MongoDatabase, and from there, MongoCollection.

Use the com.mongodb.MongoClient class if you require support for the legacy API, which supports the following features:

  • Configuration by using MongoClientOptions and MongoClientURI.

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

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

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

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

You might encounter a java.lang.NoClassDefFoundError exception when your Java runtime environment cannot locate a class file at runtime. When you attempt to run application code that uses the MongoDB Java Driver, you must include the appropriate driver JAR files on the classpath.

If you receive this error after adding the Java driver JAR files to your classpath, check the following items in your environment:

  • The JAR files exist in the locations specified by the classpath.

  • The classpath syntax is correct.

  • If you define the classpath in an environment variable, the Java runtime environment uses that variable.

  • If you use a dependency manager, it does not report any unresolvable conflicts.

Tip

This error contains the package and class name, which can help you identify which driver JAR might be missing from your classpath. To locate the driver JAR that the error refers to, check each of the entries in the API documentation.

Your application might throw this exception if you specify invalid or incorrectly formatted credentials when connecting to a MongoDB deployment.

If you receive this error when you attempt to connect to a MongoDB deployment, check the following items in your code:

  • The connection URI corresponds to the correct MongoDB deployment. To learn more about setting your connection URI, see Connection URI.

  • The credentials for the authentication mechanism that you specified are correct. To learn how to specify your credentials, see the Authentication Mechanisms and enterprise-authentication-mechanisms guides.

  • The name of the authentication database that you specified is correct. To learn how to set up the users and roles for your MongoDB deployment, see Manage Users and Roles in the Server documentation.

You might encounter this exception if you call an operation on a MongoClient instance that closed its connections to MongoDB. Once the close() method is called on the MongoClient, any further operation calls on that instance throw this exception.

To avoid this exception, do not call operations on MongoClient instance after any code that calls close() on it.

Tip

The code that closes the MongoClient instance might be difficult to locate in certain cases. To locate potential sources of this exception, search for the following cases:

  • Calls to close() on a MongoClient instance

  • Operation calls on a MongoClient instance that are outside the scope of the try-with-resources statement in which the MongoClient is declared

If your application uses a framework to manage the MongoClient such as Spring Boot, check the documentation of the framework to locate the best practices for managing the connection behavior.

To learn more about accessing MongoDB from Spring Boot, see Spring Boot and MongoDB.