Connect to MongoDB
Overview
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:
Create a new Java project in your IDE.
Install the Java Reactive Streams driver in your Java project.
Install the Project Reactor library in your Java project.
Copy the following code and paste it into a new Java file named
ConnectionApp.java
.Copy a code example from this page and paste it on the specified lines in the file.
1 import com.mongodb.ConnectionString; 2 import com.mongodb.MongoClientSettings; 3 import com.mongodb.ServerApi; 4 import com.mongodb.ServerApiVersion; 5 6 import org.bson.BsonDocument; 7 import org.bson.BsonInt64; 8 import org.bson.Document; 9 10 import com.mongodb.reactivestreams.client.MongoClient; 11 import com.mongodb.reactivestreams.client.MongoClients; 12 import com.mongodb.reactivestreams.client.MongoDatabase; 13 import org.bson.conversions.Bson; 14 import reactor.core.publisher.Mono; 15 16 class 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 }
Connection
Local Deployment
String uri = "mongodb://<hostname>:<port>/"; try (MongoClient mongoClient = MongoClients.create(uri))
Atlas
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))
Replica Set
String uri = "mongodb://<replica set member>:<port>/?replicaSet=<replica set name>"; try (MongoClient mongoClient = MongoClients.create(uri))
Sharded Cluster
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 onlocalhost: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());
Connection Options
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);