Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver

Connect to MongoDB

On this page

  • Overview
  • Connection
  • Local Deployment
  • Atlas
  • Replica Set
  • Sharded Cluster
  • Connection Options

This page contains code examples that show how to connect your Java Reactive Streams application to MongoDB with various settings.

Tip

To learn more about the connection options on this page, see the link provided in each section.

To use a connection example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <Atlas connection string>, with the relevant values for your MongoDB deployment.

Important

Project Reactor Library

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Create a new Java project in your IDE.

  2. Install the Java Reactive Streams driver in your Java project.

  3. Install the Project Reactor library in your Java project.

  4. Copy the following code and paste it into a new Java file named ConnectionApp.java.

  5. Copy a code example from this page and paste it on the specified lines in the file.

1import com.mongodb.ConnectionString;
2import com.mongodb.MongoClientSettings;
3import com.mongodb.ServerApi;
4import com.mongodb.ServerApiVersion;
5
6import org.bson.BsonDocument;
7import org.bson.BsonInt64;
8import org.bson.Document;
9
10import com.mongodb.reactivestreams.client.MongoClient;
11import com.mongodb.reactivestreams.client.MongoClients;
12import com.mongodb.reactivestreams.client.MongoDatabase;
13import org.bson.conversions.Bson;
14import reactor.core.publisher.Mono;
15
16class ConnectionApp {
17 public static void main(String[] args) {
18 //start example code here
19
20 //end example code here
21 {
22 Bson command = new BsonDocument("ping", new BsonInt64(1));
23 MongoDatabase database = mongoClient.getDatabase("admin");
24 Publisher<Document> MonoPublisher = database.runCommand(command);
25
26 Mono.from(MonoPublisher)
27 .doOnSuccess(x -> System.out.println("Pinged your deployment. You successfully connected to MongoDB!"))
28 .doOnError(err -> System.out.println("Error: " + err.getMessage()))
29 .block();
30
31 //other application code
32
33 }
34 }
35}
String uri = "mongodb://<hostname>:<port>/";
try (MongoClient mongoClient = MongoClients.create(uri))
String uri = "<Atlas connection string>";
ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
try (MongoClient mongoClient = MongoClients.create(settings))
String uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>";
try (MongoClient mongoClient = MongoClients.create(uri))

To connect to a sharded cluster, specify the mongos instance or instances to the MongoClients.create() method. To learn more about sharded clusters, see Sharding in the Server manual.

You can connect to a single mongos instance in the following ways:

  • Specify the hostname and the port in a connection string, as shown in the following code:

    MongoClient mongoClient = MongoClients.create( "mongodb://<hostname>:<port>" );
  • Exclude connection string if the mongos is running on localhost:27017, as shown in the following code:

    MongoClient mongoClient = MongoClients.create();

You can connect to multiple mongos instances in the following ways:

  • Specify the connection string to contain their hostnames and ports, as shown in the following code:

    MongoClient mongoClient = MongoClients.create("mongodb://<first hostname>:<first port>,<second hostname>:<second port>");
  • Specify a list of the ServerAddress objects corresponding to each instance, as shown in the following code:

    MongoClient mongoClient = MongoClients.create(
    MongoClientSettings.builder()
    .applyToClusterSettings(builder ->
    builder.hosts(Arrays.asList(
    new ServerAddress("<first hostname>", <first port>),
    new ServerAddress("<second hostname", <second port>))))
    .build());

You can specify connection settings by using either the connection string or MongoClientSettings types, or both.

For example, you can specify TLS/SSL and authentication settings in the connection string, as shown in the following code:

MongoClient mongoClient = MongoClients.create("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");

You can also use a MongoClientSettings instance to specify TLS/SSL and the MongoCredential type to store the authentication information, as shown in the following code:

String user; // the username
String database; // the name of the database in which the user is defined
char[] password; // the password as a character array
// ...
MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientSettings settings = MongoClientSettings.builder()
.credential(credential)
.applyToSslSettings(builder -> builder.enabled(true))
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress("host1", 27017))))
.build();
MongoClient mongoClient = MongoClients.create(settings);

In some cases, you might need to combine a connection string with programmatic configuration, as shown in the following code:

ConnectionString connectionString = new ConnectionString("mongodb://host1:27107,host2:27017/?ssl=true");
CommandListener myCommandListener = ...;
MongoClientSettings settings = MongoClientSettings.builder()
.addCommandListener(myCommandListener)
.applyConnectionString(connectionString)
.build();
MongoClient mongoClient = MongoClients.create(settings);

Back

Next Steps