How to connect MonogDB in Java?

Connect with

How to connect MonogDB in JavaHow to connect MongoDB in Java using maven, eclipse is easy so learn connecting MongoDB in Java. connection using native MongoClient, mongoTemplate etc.

1. Overview of connect MongoDB in Java

There is so many languages’ driver in MongoDB to connect to perform CRUD operations. Here CRUD means: Create, Read, Update, Delete operations. These are the four basic and fundamental operations which we use to do every day so many times during developent.
There are different ways to connect MongoDB in Java, it depends upon many factors which are as:

  • installed in localhost
  • installed on stand-alone server
  • installed and configured in MongoDB replica set
  • installed and configured sharding of MongoDB

Secondly, to consider connecting to MongoDB in Java, whether you want to connect by native mongoClient or mongoTemplate in Spring framework or any other approach. I tried to explain a few easy steps by step process in this article.

2. Pre-requisite of MongoDB connection in Java

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

3. Maven Dependency for mongoDB connection in Java

Add following mongoDB driver dependency in your pom.xml



  org.mongodb
  mongo-java-driver
  2.13.1

4. 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 prints 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

5. 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)));

6. Connecting to mongoDB with auth using MongoClient

By the time of this article, latest version of mongoDB is 3.2, so in this example of mongoDB connection in Java, version of mongoDB 3.2 which by default use SHRAM-SHA-1 authentication mechanism so used SHRAM-SHA-1 specific class which driver provides us.
First of all, as an admin, you need to add an admin user in the MongoDB database i.e. in the admin database or respective database, here ‘myblogdb’ is a database in MongoDB on which user i.e. ‘myblogUser’ has readWrite privilege. You can visit 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 {
   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();
  }
}

You can visit docs.mongodb.com for more details.

Related Post:

Happy Learning! 🙂


Connect with

Leave a Comment

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