A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/connect-to-mongodb/ below:

Connect to MongoDB

Connect to MongoDB

Use MongoClient() to make a connection to a running MongoDB instance.

important

The following examples are not meant to provide an exhaustive list of ways to instantiate MongoClient. For a complete list of the MongoClient constructors, see MongoClient() API documentation.

Prerequisites MongoClient

The MongoClient() instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

important

Typically you only create one MongoClient instance for a given MongoDB deployment (e.g. standalone, replica set, or a sharded cluster) and use it across your application. However, if you do create multiple instances:

Connect to a Standalone MongoDB Instance

To connect to a standalone MongoDB instance:

Connect to a Replica Set

To connect to a replica set, you must specify one or more members to the MongoClient constructor.

Note

MongoDB will auto-discover the primary and the secondaries.

Connect to a Sharded Cluster

To connect to a sharded cluster, specify the mongos instance or instances to the MongoClient constructor.

To connect to a single mongos instance:

To connect to multiple mongos instances:

Connection Options

You can specify the connection settings using either the MongoClientURI or MongoClientOptions or both.

For example, you can specify TLS/SSL and authentication setting in the MongoClientURI connection string:

MongoClientURI uri = new MongoClientURI("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true");
MongoClient mongoClient = new MongoClient(uri);

You can also use MongoClientOptions to specify TLS/SSL and the MongoCredential for the authentication information:


 String user; // the user name
 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);

 MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true).build();

 MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017),
                                           Arrays.asList(credential),
                                           options);

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4