Web Programming TutorialsLearn How to Create and Select Collections in MongoDB using Java

Learn How to Create and Select Collections in MongoDB using Java

Select Collections
In this chapter, we are going to look at MongoDB JDBC driver in order to connect MongoDB database with JAVA. We will set up environment first to connect MongoDB via JDBC connection and after successfully connection with MongoDB and JAVA, we are going to create and select a collection in MongoDB through JAVA programming language.

Downloading MongoDB JDBC driver
We can download the MongoDB JDBC Jar file from the following link. If you are using Maven to build your java project, then you just need to copy the dependency code into pom.xml file, which will automatically download the MongoDB JDBC driver and build your project.
https://mongodb.github.io/mongo-java-driver/
Mongo-Java-Driver
In this article, we are going to manually download the jar [mongodb-java-driver-3.4.2.jar] and build path in eclipse in to make JDBC connection with MongoDB.

DB Connection Environment Setup
Step 1: – Start the MongoDB by following the steps stated in the earlier article of this tutorial series.
Step2: – Once MongoDB is started on your local or remote machine. Open eclipse and set up your workspace as shown below.
Select a Workspace
Step 3: – Open the ‘project wizard’ in eclipse and select a ‘new Java Project’ as shown below.
java project
Step 4: – Click the Next button. Give the project name as ‘java-mongodb-project’ and make sure that you have chosen appropriate JAVA runtime environment (here Java 1.8) as shown in the below screenshot.
java-mongodb-project
Step 5: – Click the Finish button. At this point, you may observe that a Java project has been created on the left hand side in the project explorer section with the name provided in the Step 4.
Step 6: – Right click on the project and choose ‘Build Path -> Configure Build Path’ from the menu as shown below.
Configure Build Path
Step 7: – It will open up a dialogue box to build a Java Path as shown below. Choose the ‘Libraries’ tab and click on the ‘Add external JARS…’ button to add ‘mongodb-java-driver-3.4.2.jar’ which was downloaded earlier in this article.
JRE System Library
Step 8: – Once added, click on the ‘Apply’ button to apply the Jar at the project build path and click on the ‘OK’ button. This will complete the adding of the MongoDB JDBC jar to the project as shown below.
MongoDB JDBC jar
Step 9: – Right click on the ‘src’ directory and navigate ‘New -> Class’ as shown below.
New Class
Step 10: – It will open up ‘New Java Class’ dialogue box as shown below. Add a package name ‘com.edunoix.db’, Class name ‘MongoDBJDBCConnection’ and other options as shown below. Click the ‘Finish’ button.
New Java Class
At this point, our environment set up is completed and now we need to write the JAVA code for JDBC Connection with MongoDB.
Code for JDBC Connection
JAVA – MONGODB JDBC Connection
MongoDBJDBCConnection.java

package com.edunoix.db;

import com.mongodb.DB;
import com.mongodb.MongoClient;

public class MongoDBJDBCConnection {

	public static void main(String args[]) {
		try {
			/**** Connect to the MongoDB ****/
			// Since 2.10.0, uses MongoClient
			MongoClient mongodb  = new MongoClient("localhost", 27017);

			/**** Get database ****/
			// if database doesn't exists, MongoDB will create it for us
			@SuppressWarnings("deprecation")
			DB db = mongodb.getDB("testdb");
			System.out.println("Connect to database successfully");
			
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
	}
}

Before executing this program, make sure that the MongoDB instance is running on your local or remote machine. Here, the MongoDB instance is running on the local machine at port 27017.

Explanation of Code

  • Firstly, we are connecting with the MongoDB client through MongoClient class by passing the URL (here localhost) and port where MongoDB instance is running.
  • The MongoDB instance is returned in mongodb instance variable. It is used to invoke DB instance through ‘mongodb.getDB (“testdb”)’ method into ‘db’ instance variable.
  • The entire code is placed inside the try catch block in order to catch any possible exception thrown during runtime of this Java program.

Output
When we execute above JAVA program, it will connect to the MongoDB as shown below on the console.

Feb 04, 2017 2:11:49 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connect to database successfully

This Java program will accomplish the following operations.

  • Connect to the MongoDB present at the localhost and port 27017.
  • Connect to the database ‘testdb’. If such database does not exist, then it will create a new database with this name.

MongoDB – Creation and Selection of a Collection
With the help of last Java program, we were able to connect to MongoDB and the ‘testdb’ database. Now, we are going to select a collection present in the MongoDB’s ‘testdb’ database through the JAVA Programming as shown below.

MongoDBCollection.java

package com.edunoix.db;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class MongoDBCollection {

	public static void main(String args[]) {
		try {
			/**** Connect to the MongoDB ****/
			MongoClient mongodb = new MongoClient("localhost", 27017);

			/**** Get database ****/
			// if database doesn't exists, MongoDB will create it for us
			@SuppressWarnings("deprecation")
			DB db = mongodb.getDB("testdb");
			System.out.println("Connection to MongoDB database successfully");
			
			/**
			 * Selecting Collection from MongoDB
			 */
			DBCollection coll = db.getCollection("MyCollection1");
			System.out.println("Collection has selected successfully");
			
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
	}
}

Output
When we execute the above JAVA program, it will connect to the MongoDB and do the selection operation on the ‘MyCollection1’ collection present in the MongoDB as shown below on the console.

Feb 04, 2017 4:23:20 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connection to MongoDB database successfully
Collection has selected successfully

This Java program will accomplish the following operations.

  • Connect to the MongoDB present at the localhost and port 27017.
  • Connect to the database ‘testdb’. If such database does not exist, then it will create a new database with this name.
  • Select a collection named ‘MyCollection1’ that exists in the MongoDB.

Source code for the blog: – Creation and selection

Conclusion: –
In this tutorial, we have discussed about MongoDB JDBC connection environment set up and used this environment to select a collection from the MongoDB.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -