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

Create a MongoClient

On this page

  • Overview
  • Connection URI
  • MongoClient
  • API Documentation

To connect to a MongoDB deployment, you need two things:

  • A connection URI, also known as a connection string, which tells the Java Reactive Streams driver which MongoDB deployment to connect to.

  • A MongoClient instance, which creates connections to the MongoDB deployment and lets you perform operations on it.

You can also use either of these components to customize the way the Java Reactive Streams driver behaves while connected to MongoDB.

This guide shows you how to create a connection string and use a MongoClient instance to connect to MongoDB.

A standard connection string includes the following components:

Component
Description
mongodb://
Required. A prefix that identifies the URI as a string in the standard connection format.
username:password

Optional. Authentication credentials. If you include these, the client authenticates the user against the database specified in authSource.

For more information about the authSource connection option, see the Authentication guide.

host[:port]
Required. The host and port number where MongoDB is running. If you don't include a port number, the driver uses the default port, 27017.
/defaultauthdb
Optional. The authentication database to use if the connection string includes username:password@ authentication credentials but not the authSource option. If you don't include this component, the client authenticates the user against the admin database.
?<options>

Optional. A query string that specifies connection-specific options as <name>=<value> pairs.

For a full description of these options, see the Specify Connection URI Options guide.

For more information about creating a connection string, see Connection Strings in the MongoDB Server documentation.

To create a connection to MongoDB, pass a connection URI as a string to the method constructing a MongoClient object. In the following example, the driver uses a sample connection URI to connect to a MongoDB instance on port 27017 of localhost:

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
}
}
}

Tip

Reusing Your Client

Because each MongoClient instance pools connections to the database, most applications require only a single instance of MongoClient, even across multiple requests.

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

Back

Connect to MongoDB