Docs Menu

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

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.

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 MongoClientConnectionExample {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "mongodb://user:pass@sample.host:27017/?maxPoolSize=20&w=majority";
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.
Important

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 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 →
Give Feedback
© 2022 MongoDB, Inc.

About

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