How to connect MonogDB in Java?

Connect with

MongoDB
There are different way to connect the mongoDB in Java , it depends upone many factor, whether it’s stand alone server or installed in localhost or installed and configured in mongoDB replica set or sharding of mongoDB. Secondly, to consider of connecting to mongDB in java, whether by native mongoClient or mongoTemplate in Spring framework or any another approach. I tried to explain few easy step by step process in this article.

1. Pre-requisite of Connecting mongoDB

Assuming you have mongoDB installed in your local system or any another server. if not, please visit my another post.

2. Maven Dependency

Add following mongoDB driver dependency in your pom.xml



  org.mongodb
  mongo-java-driver
  2.13.1

3. Connecting MongoDB without Auth using MongoClient

By connecting with mongoDB print list of dbname on console is our objective in this demo.

/**
 * This method is used to demonstrate how to connect mongoDB database 
 * without auth , it means anonymously and print all the database available,
 */
public void connectWithoutAuth()  {
	try {
	// provide IP/hostname or port to connect mongoDB server
	MongoClient mongoClient = new MongoClient( "10.0.8.20", 27017 );
	
	List dbList = mongoClient.getDatabaseNames();
	for(String dbName : dbList) {
		System.out.println("dbName: " + dbName);
	}
		
	} catch (Exception e) {
	  e.printStackTrace();
	}
}

Output of console:

dbName: admin
dbName: local
dbName: test

4. Different way to provide IP/hostName or port

with Default argument:

/* 
 * To directly connect to a single MongoDB local server , 
 * by default hostName will be localhost and port 27017 
 * if you not provided in the MongoClient argument.
 */
MongoClient mongoClient = new MongoClient();

With IP Address or host name and specified port:

// provide IP/hostname or port to connect mongoDB
MongoClient mongoClient = new MongoClient( "10.0.8.20", 27017 );
	

Explicitly provide hostName/IP and MongoDB service port:

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

provide seed list to connect ReplicaSet

// provide seed list node of replica member where replica set configured, to connect replica set
MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("10.0.0.1", 27017),
   new ServerAddress("10.0.0.2", 27018), new ServerAddress("10.0.0.3", 27019)));

5. Connecting to mongoDB with auth using MongoClient

In this demo , mongoDB 3.2 which by default use SHRAM-SHA-1 authentication mechanism so used SHRAM-SHA-A specific class which driver provides us.
First of all, as a admin you need to add admin user in the mongoDB database i.e. in admin database and respective database, here ‘myblogdb’ is a databasse in mongoDB on which user i.e. ‘myblogUser’ has readWrite privilege. You can visit my another article , how to add and drop user in mongoDB

/**
 * This method is used to get connect to mongoDB by using SCRAM-SHA-1 authentication mechanism.
 */
public void connectWithAuth() {
	try {
		
	// using release 2.13 or later
	//MongoCredential credential = MongoCredential.	("mycore", "coreService", "abc123".toCharArray());

	// using release 2.11 or 2.12 till 2.6 of mongoDB
	// if authentication Mechanism is MONGODB-CR then user following	
	//MongoCredential credential = MongoCredential.createMongoCRCredential("myblogUser", "admin", "secret".toCharArray());
	
	// if authentication Mechanism is SCRAM-SHA-1 then user following, 
	//by default from mongodb 3.0 and ownward uses SCRAM-SHA-1 authentication mechanism
	MongoCredential credential = MongoCredential.createScramSha1Credential("myblogUser", "myblogdb", "secret".toCharArray());
	MongoClient mongoClient = new MongoClient(new ServerAddress("10.0.8.20"), Arrays.asList(credential));

	DB db = mongoClient.getDB("myblogdb");
	DBCollection coll = db.getCollection("blog");
	
	System.out.println("total count in collection: " + coll.getCount());
	
	// Get added Data and print on console
	DBCursor cursor = coll.find();
	while(cursor.hasNext()) {
		System.out.println(cursor.next());
	}
	
	} catch (Exception e) {
		e.printStackTrace();
	}
}

Related Post:


Connect with

Leave a Reply

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