mongoDB connection in java

1. Overview of mongoClient

MongoDB support internal connection pooling in different ways, one of the way is using MongoClient. You can create MongoClient in your java code in different ways:
with default localhost, with default port , with provided or customized host/ip and default port (i.e. 27017) , with default host (i.e. localhost) with provided/customized port.
Ideally, you should have only one instance of mongoClient in one JVM in your application which connect with one database. If you wanted to connect with different databases then obviously you should have multiple instance of mongoClient. It means, you can keep mongoClient instance per database connection. Keeping of mongoClient per database is not hard and fast rule, people keep mongoClient instance as per convenient and need. But, I strongly prefer, instance of mongoClient per database which are manageable.

2. different way of connection using mongoClient

The following are equivalent, and all connect to the local database running on the default port:

2.1 connection with implicitly, default host i.e. localhost and default port (i.e. 27017)

 MongoClient mongoClient = new MongoClient();

2.2 connection with explicitly provided host i.e. localhost and default port (i.e. 27017)

 MongoClient mongoClient = new MongoClient("localhost");

2.3 connection with explicitly provided default host i.e. localhost and provided default port (i.e. 27017)

 MongoClient mongoClient = new MongoClient("localhost", 27017);

2.4 connection with explicitly provided default host i.e. localhost with serverAddress and provided default port (i.e. 27017)

 MongoClient mongoClient = new MongoClient(new ServerAddress("localhost"));

2.5 connection with explicitly provided default host (i.e. localhost) with serverAddress, MongoClientOptions and provided default port (i.e. 27017)

 MongoClient mongoClient5 = new MongoClient(new ServerAddress("localhost"), new MongoClientOptions.Builder().build());

You can connect to a replica set using the Java driver by passing a ServerAddress list to the MongoClient constructor. For example:

2.6 connection with explicitly provided multiple default host (i.e. localhost) with multiple serverAddress , and provided customized port (i.e. 27017, 27018, 27019).

 MongoClient mongoClient = new MongoClient(Arrays.asList(
   new ServerAddress("localhost", 27017),
   new ServerAddress("localhost", 27018),
   new ServerAddress("localhost", 27019)));

2.7 connection with explicitly provided multiple IP address and provided customised port (i.e. 27017, 27018, 27019).

 MongoClient mongoClient = new MongoClient(Arrays.asList(
   new ServerAddress("10.1.20.1", 27017),
   new ServerAddress("10.1.20.2", 27018),
   new ServerAddress("10.1.20.3", 27019)));

2.8 connection with explicitly provided multiple hosts and provided customized port (i.e. 27017, 27018, 27019).

 MongoClient mongoClient = new MongoClient(Arrays.asList(
   new ServerAddress("mongodb1.mysoftkey.com", 27018),
   new ServerAddress("mongodb2.mysoftkey.com", 27018),
   new ServerAddress("mongodb3.mysoftkey.com", 27016)));

3. mongoDB connection with ReplicaSet and authentication

File: MongoConnection.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.mysoftkey.poc;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
 
/**
 *  This class is used to create the connection of mongoDB.
 *
 * @author Ranjeet Jha
 *
 */
public class MongoConnection {
 
  MongoClient mongoClient = null;
 
  public static void main(String[] args) {
 
  }
 
  /**
   * This method returns mongoClient for the provided details,
   * for replicaSet name and readPreference secondaryPreferred.
   * with SCRAM-SHA-1 authentication mechanism.
   * 
   * @return
   */
  public MongoClient getMongoClientInReplicasetWithAuth() {
    int connectionsPerHost = 50;
    int connectionTimeOut = 3000; // 3 sec
	int socketTimeOut = 6000; // 6sec
	String replicaSetName = "mysoftkeyRS";
	String dbName = "myDB";
	String userName = "dbUser";
	String password = "dbUser12345";
	String host = "10.";
	int portNo = 27017;
 
	try {
	  MongoClientOptions options = MongoClientOptions.builder()
		.readPreference(ReadPreference.secondaryPreferred()).requiredReplicaSetName(replicaSetName)
		.connectionsPerHost(connectionsPerHost).connectTimeout(connectionTimeOut)
		.socketTimeout(socketTimeOut).build();
 
	  // if using less than 3.0 of mongodb version then use mongoCR and for greater than or equal to 3.0 version use ScramSha1
	  MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName . password.toCharArray());
 
	  String array[] = host.split(",");
	  List<ServerAddress> serverAddress = new ArrayList<ServerAddress>();
	  for (String str : array) {
	    serverAddress.add(new ServerAddress(str, portNo));
	  }
	  mongoClient = new MongoClient(serverAddress, Arrays.asList(credential), options);
	  } catch (Exception e) {
		System.err.println("exception caught while connecting mongoDB, msg: " + e.getMessage());
	  } 
	return mongoClient;
 
   }
}

4. connection with MongoCR credential

connection strategies for authentication in mongodb for less than 3.0 was different than than 3 or above version.

 /**
   * This method returns mongoClient for the provided details,
   * for replicaSet name and readPreference secondaryPreferred.
   * if using less than 3.0 of mongodb version then use mongoCR and for greater than or equal to 3.0 version use ScramSha1
   * @return
   */
  public MongoClient getMongoClientInReplicasetWithAuth() {
    int connectionsPerHost = 50;
    int connectionTimeOut = 3000; // 3 sec
	int socketTimeOut = 6000; // 6sec
	String replicaSetName = "mysoftkeyRS";
	String dbName = "myDB";
	String userName = "dbUser";
	String password = "dbUser12345";
	String host = "10.";
	int portNo = 27017;
 
	try {
	  MongoClientOptions options = MongoClientOptions.builder()
		.readPreference(ReadPreference.secondaryPreferred()).requiredReplicaSetName(replicaSetName)
		.connectionsPerHost(connectionsPerHost).connectTimeout(connectionTimeOut)
		.socketTimeout(socketTimeOut).build();
 
	  MongoCredential credential =  MongoCredential.createMongoCRCredential(userName, dbName, password.toCharArray());
 
	  String array[] = host.split(",");
	  List<ServerAddress> serverAddress = new ArrayList<ServerAddress>();
	  for (String str : array) {
	    serverAddress.add(new ServerAddress(str, portNo));
	  }
	  mongoClient = new MongoClient(serverAddress, Arrays.asList(credential), options);
	  } catch (Exception e) {
		System.err.println("exception caught while connecting mongoDB, msg: " + e.getMessage());
	  } 
	return mongoClient;
 
   }
}

You are comments are welcome to improve this post. Happy Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *