Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver
/

Choose a Connection Target

On this page

  • Overview
  • Atlas
  • Local Deployments
  • Replica Sets
  • Initialization
  • API Documentation

In this guide, you can learn how to use a connection string and a MongoClient object to connect to different types of MongoDB deployments.

To connect to a MongoDB deployment on Atlas, include the following elements in your connection string:

  • URL of your Atlas cluster

  • MongoDB username

  • MongoDB password

Then, pass your connection string to the create() method constructing a MongoClient object.

Tip

Follow the Atlas driver connection guide to retrieve your connection string.

When you connect to Atlas, we recommend using the Stable API client option to avoid breaking changes when Atlas upgrades to a new version of MongoDB Server. To learn more about the Stable API feature, see Stable API in the MongoDB Server manual.

The following code shows how to use the Java Reactive Streams driver to connect to an Atlas cluster. The code uses the serverApi option to specify a Stable API version.

Important

Reactor Library Methods

This guide uses methods from the Reactor Library, a library based on the Reactive Streams specification. To install Reactor, see Getting Reactor in the Project Reactor documentation.

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.ServerApi;
import com.mongodb.ServerApiVersion;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.bson.conversions.Bson;
import reactor.core.publisher.Mono;
public class testing {
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("<database name>");
Bson command = new BsonDocument("ping", new BsonInt64(1));
Mono.from(database.runCommand(command))
.doOnSuccess(x -> System.out.println("Pinged your deployment. You successfully connected to MongoDB!"))
.doOnError(err -> System.out.println("Error: " + err.getMessage()))
.block();
}
}
}

To connect to a local MongoDB deployment, use localhost as the hostname. By default, the mongod process runs on port 27017, though you can customize this for your deployment.

The following code shows how to use the Java Reactive Streams driver to connect to a local MongoDB deployment:

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
public class MongoConnection {
public static void main(String[] args) {
String uri = "mongodb://localhost:27017/";
try (MongoClient client = MongoClients.create(uri)) {
// use `client` here
}
}
}

To connect to a replica set, specify the hostnames (or IP addresses) and port numbers of the replica-set members in your connection string.

If you aren't able to provide a full list of hosts in the replica set, you can specify one or more of the hosts in the replica set and instruct the Java Reactive Streams driver to perform automatic discovery to find the others. To instruct the driver to perform automatic discovery, perform one of the following actions:

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

In the following example, the driver uses a sample connection URI to connect to the MongoDB replica set sampleRS, which is running on port 27017 of three different hosts, including host1:

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
public class MongoConnection {
public static void main(String[] args) {
String uri = "mongodb://localhost:27017/?replicaSet=sampleRS";
try (MongoClient client = MongoClients.create(uri)) {
// use `client` here
}
}
}

Note

create() is Non-Blocking

The create() method constructing a MongoClient is non-blocking. When you connect to a replica set, the method returns immediately while the client uses background threads to connect to the replica set.

If you create a MongoClient and immediately print the string representation of its nodes attribute, the list might be empty while the client connects to the replica-set members.

To initialize a replica set, you must connect directly to a single member. To do so, set the directConnection connection option to True. You can do this in the following ways:

  • Passing an argument to the create() method constructing a MongoClient

  • Setting the parameter in your connection string.

import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
public class MongoConnection {
public static void main(String[] args) {
try (MongoClient client =
MongoClients.create("mongodb://<hostname>:<port>", directConnection=True)){
// use `client` here
}
}
}
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
public class MongoConnection {
public static void main(String[] args) {
String uri = "mongodb://<hostname>:<port>/?directConnection=true";
try (MongoClient client = MongoClients.create(uri)){
// use `client` here
}
}
}

To learn more about creating a MongoClient instance in the Java Reactive Streams driver, see the following API documentation:

Back

Create a MongoClient