Connect to MongoDB
On this page
This guide describes how to use the Java Reactive Streams driver to connect to MongoDB.
Use the MongoClients.create()
method to make a connection to a
running MongoDB deployment.
Important
The following examples do not provide an exhaustive list of
ways to instantiate a MongoClient
. For a complete list of the
MongoClient
factory methods, see the MongoClients API
documentation.
Note
We strongly recommended that system keep-alive settings should be configured with shorter timeouts.
See the Does TCP keepalive time affect MongoDB Deployments? question and answer in the Server manual FAQ for more information.
Prerequisites
You must set up the following components to run the code examples in this guide:
A running MongoDB deployment to connect to. For example, to connect to a standalone deployment, you must have access to a running standalone deployment.
Driver dependency installed in your project. To learn how to install the driver, see the installation guide.
The following import statements:
import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.MongoClientSettings; import com.mongodb.ConnectionString; import com.mongodb.ServerAddress; import com.mongodb.MongoCredential; import java.util.Arrays;
MongoClient
A MongoClient
instance represents a pool of connections to the
database. You need only one instance of MongoClient
even
when running multiple concurrent operations.
Important
Typically, you create only one MongoClient
instance for a given
MongoDB deployment, such as a standalone deployment, replica set, or a sharded
cluster, and use the client across your application. However, if you do create
multiple instances, keep the following in mind:
All resource-usage limits (for example, max connections) apply to each
MongoClient
instance.To dispose of an instance, call the
MongoClient.close()
method to clean up resources.
Connect to a Standalone MongoDB Deployment
The following example shows several ways to connect to a single MongoDB deployment.
You can connect to a single MongoDB deployment in the following ways:
Instantiate a
MongoClient
object without any parameters to connect to a MongoDB server running on localhost on port27017
:MongoClient mongoClient = MongoClients.create(); Explicitly specify the
hostname
to connect to a MongoDB instance running on the specified host on port27017
:MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("hostOne")))) .build()); Explicitly specify the
hostname
and theport
:MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList(new ServerAddress("hostOne", 27018)))) .build()); Specify the
ConnectionString
:MongoClient mongoClient = MongoClients.create("mongodb://hostOne:27017");
Connect to a Replica Set
To connect to a replica set, you must specify one or more
members to the MongoClients.create()
method. To learn more about
replica sets, see Replication in the Server
manual.
Note
MongoDB auto-discovers the primary and secondary nodes in a replica set.
You can connect to a MongoDB replica set by specifying the members in
a ConnectionString
.
The following example shows how to specify three members of the replica set:
MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017");
The following example shows how to specify members of the
replica set and the replicaSet
option with the replica set
name:
MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet");
The following example shows how to specify a list of
ServerAddress
instances corresponding to all of the replica
set members:
MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList( new ServerAddress("host1", 27017), new ServerAddress("host2", 27017), new ServerAddress("host3", 27017)))) .build());
Connect to a 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
ConnectionString
:MongoClient mongoClient = MongoClients.create( "mongodb://localhost:27017" ); Exclude connection string if the
mongos
is running onlocalhost:27017
:MongoClient mongoClient = MongoClients.create();
You can connect to multiple mongos
instances in the following ways:
Specify the
ConnectionString
to contain their hostnames and ports:MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017"); Specify a list of the
ServerAddress
objects corresponding to each instance:MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder() .applyToClusterSettings(builder -> builder.hosts(Arrays.asList( new ServerAddress("host1", 27017), new ServerAddress("host2", 27017)))) .build());
Connection Options
You can specify connection settings by using either the
ConnectionString
or MongoClientSettings
types, or both.
For example, you can specify TLS/SSL and authentication settings in the connection string:
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:
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:
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);