mongoDB connection in java

Connect with

MongoDB connection using javaHow to connect MongoDB in java programming language is simple by using MongoDB driver. You need to provide a List of IP(s) in replication or in standalone you have to provide IP or domain or machine name along with the port on which you listen mongod service.

1. Overview of mongoClient

MongoDB supports internal connection pooling in different ways, one of the ways is using MongoClient. You can create MongoClient in your java code for MongoDB connection using Java in different ways:
with default localhost, with a 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 connects with one database. If you wanted to connect with different databases then obviously you should have multiple instances of mongoClient. It means you can keep mongoClient instance per database connection. Keeping of mongoClient per database is not a hard and fast rule, people keep mongoClient instance as per convenience and need. But, I strongly prefer, instances 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

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 = new ArrayList();
	  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 = new ArrayList();
	  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 🙂


Connect with

1 thought on “mongoDB connection in java”

Leave a Comment

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