Being a cross-platform document-first NoSQL database program, MongoDB operates on JSON-like documents. On the other hand, JDBC is a Java application programming interface (API) used while executing queries in association with the database.

Using JDBC, you can seamlessly access any data source from any relational database in spreadsheet format or a flat file. In fact, all major service providers have their own JDBC drivers, which include different sets of Java classes to enable a particular connection to a particular database. Using the MongoDB JDBC connectivity, it’s easier to place a query with the database, introduce updates to the database, and call upon stored processes.

In this tutorial article, we will explore the MongoDB JDBC connect in detail. And to maintain a coerce understanding of the subject, introduce you to the concept of JDBC Connector and the basics and features of MongoDB in brief. Let’s begin.

What is MongoDB?

MongoDB JDBC Connect MongoDB logo

MongoDB is a document-oriented no-SQL database. Initially released in 2009, MongoDB has successfully altered the concept of rows and columns in conventional relational data models with documents.

MongoDB provides today’s developers with the flexibility to work with evolving data models because its document-based and, allows embedded documents, arrays, and represents complex hierarchical data structures and relationships using a single record.

Moreover, the fact that MongoDB is schema-free, the keys defined in the documents are not fixed; hence, data migration at a large scale can be ruled out. MongoDB stores data in BSON format, which is similar to JSON. A basic document storage structure looks like this:

{
  title: 'Geeksforgeeks',
  by: 'Harshit Gupta',
  url: 'https://www.geeksforgeeks.org',
  type: 'NoSQL'
} 

Some key features of MongoDB are as follows:

It’s Document-oriented: MongoDB does not break documents into multiple relational structures like RDBMS but instead stores the main subject in a minimal number of documents. It stores data in documents named “Computer” and not in CPU, RAM, Hard disk, etc. which are relational structures.

It’s a General Purpose Database with Flexible Schema Design: MongoDB can execute heterogeneous loads and multiple purposes within an application. Its document-oriented approaches with non-defined attributes that can be modified on the fly are a key contrast between MongoDB and any other relational database.

It’s Scalable: MongoDB is built to scale both horizontally and vertically. In terms of horizontal scalability, MongoDB uses sharding, and architecture users can share the load between multiple instances, achieving both read and write scalability. Load-balancing also happens automatically and transparently to the user by the shared balancer eliminating the need for complex data pipelines.

What is a JDBC Connector?

MongoDB JDBC Connect JDBC logo

JDBC stands for Java DataBase Connectivity. JDBC is a Java API that is used to connect and execute queries with the database. Developers use JDBC to access any kind of tabular, also including the data stored in a Relational Database.

JDBC is generally used to connect java applications with databases and is usually installed automatically with the JDK software. On the other hand, the JDBC connector is a program that makes various possible databases to get accessed by Java application servers, run on Java 2 Platform, which is an enterprise edition Java programming language from Sun Microsystems.

How to Establish MongoDB JDBC Connect?

In this section, you will go through the steps to set up a connection. To establish a Connect, follow the seven steps given below:

Step 1: Add the JDBC Driver JAR files in Eclipse

In the development phase, while establishing the MongoDB JDBC connect, it’s required to ensure that the JDBC Driver is added to the built path. To add JDBC driver to the built path, first, click on the package name in the Package Explorer section, then hit “Alt” + “Enter” and click on Java Build Path.

Now, find and click on the “As External JARs” button and then find the newly downloaded JDBC Driver jar files. In the example given below, we are using MongoDB; hence we will choose unityjdbc.jar in addition to the mongo-java-driver-2.12.2.jar.

MongoDB JDBC Connect
MongoDB JDBC Connect

Step 2: Import Java.SQL Package

Until now in the process to establish Connect, we have successfully added an appropriate JDBC driver to the Java Built Path. Now, it’s required to import the java.sql.* classes as well for MongoDB JDBC connect.

The import statements given below will declare Java Class(es) import statements. After declaring the Java class, the class name is used, in the code, without having to classify the package it belongs to.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

A simple import statement can also be used as shown in the code below:

import java.sql.*;

Step 3: Next, Register the Database Driver

First, to begin using the MongoDB JDBC Connect, it’s necessary to register the driver. Use the “Class.forName” method to register, as shown in the example below:

try {
  Class.forName("mongodb.jdbc.MongoDriver");
} catch (ClassNotFoundException e) {
  System.out.println("ERROR: Unable to load SQLServer JDBC Driver");
  e.printStackTrace();
  return;
}

Step 4: Create the Database Connection

Now that we have the MongoDB JDBC connection registered, it’s required to establish the connection to the database. Use the “DriverManager.getConnection” method as shown in the example below:

<code>

Step 5: Create the JDBC Statement

Now the MongoDB JDBC connect is ready to use and get interact with. Use the JDBC createStatement(), prepareCall(), & prepareStatement() methods to establish a back and forth MongoDB JDBC connection that enables you to send and receive data in your database. Look at the code given below:

try {
       connection = DriverManager.getConnection(database_url, username, password);
    } catch (SQLException e) {
      System.out.println("ERROR:  Unable to establish a connection with the database!");
      e.printStackTrace();
      return;
    }

Step 6: Now, Iterate Through the ResultSet

The ResultSet has records of data returning from a database query that is already executed. Now, when looking at the JavaDocs, a ResultSet is maintained and a cursor is pointing to its current row of data. At first glance, the cursor seems to be positioned before the first row. Now the “next” method is used to move the cursor to the next row.

Look at the code given below for Integration to understand better:

try{
  statement = connection.createStatement();
  result = statement.executeQuery("select employee_id, first_name, last_name from employee");

  while (result.next()) {
    String employee_id = result.getString("employee_id");
    String first_name  = result.getString("first_name");
    String last_name  = result.getString("last_name");
    System.out.printf("Employee ID: [%s], %s %s n", employee_id, first_name, last_name);
  }
} catch (SQLException e) {
   System.out.println(e.getMessage());
}

Step 7: At Last, Close the Connection

It’s necessary to ensure that the database connections and the resources at the end of the program are closed. It’s considered to be a poor programming practice if not able to comply. Look at the code given below:

} finally {
  if (connection != null) connection.close();
}

Moreover, a sample JDBC program to establish MongoDB JDBC connect looks like this:

package com.avaldes.tutorials;
 
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class MongoJDBCExample {
 
public static void main(String[] args) throws SQLException {
String database_url = "jdbc:mongo://localhost:27017/tutorial";
String username = "webuser";
String password = "webuser123";
Connection connection = null;
Statement statement = null;
ResultSet result = null;
 
try {
Class.forName("mongodb.jdbc.MongoDriver");
} catch (ClassNotFoundException e) {
System.out.println("ERROR: Unable to load SQLServer JDBC Driver");
e.printStackTrace();
return;
}
System.out.println("MongoDB JDBC Driver has been registered...");
 
System.out.println("Trying to get a connection to the database...");
try {
connection = DriverManager.getConnection(database_url, username, password);
} catch (SQLException e) {
System.out.println("ERROR: Unable to establish a connection with the database!");
e.printStackTrace();
return;
}
 
if (connection != null) {
DatabaseMetaData metadata = connection.getMetaData();
System.out.println("Connection to the database has been established...");
System.out.println("JDBC Driver Name : " + metadata.getDriverName());
System.out.println("JDBC Driver Version : " + metadata.getDriverVersion());
} else {
System.out.println("ERROR: Unable to make a database connection!");
}
 
System.out.println("Trying to get a list of all employees in employee collection...");
try {
statement = connection.createStatement();
 
String sql = "select employee_id, first_name, last_name from employee";
result = statement.executeQuery(sql);
 
while (result.next()) {
int employee_id = result.getInt("employee_id");
String first_name = result.getString("first_name");
String last_name = result.getString("last_name");
 
System.out.printf("EMPLOYEE_ID: [%d], %s %s n", employee_id, first_name, last_name);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Closing all open resources...");
if (result != null) result.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
}
}

And, the output for MongoDB JDBC connect looks like this:

License Issued date: Sat Nov 22 11:03:37 EST 2014
Trial End date: Tue Dec 23 03:00:00 EST 2014
MongoDB JDBC Driver has been registered…
Trying to get a connection to the database…
Connection to the database has been established…
JDBC Driver Name : Mongo JDBC
JDBC Driver Version : 1.0
Trying to get a list of all employees in employee collection…
EMPLOYEE_ID: [1], Alex Smith
EMPLOYEE_ID: [2], David Harvey
EMPLOYEE_ID: [3], Lisa Bank
EMPLOYEE_ID: [4], James Young
EMPLOYEE_ID: [5], Danielle Gray
EMPLOYEE_ID: [6], Jeff Wang
EMPLOYEE_ID: [7], Rishi Patel
EMPLOYEE_ID: [8], Karen Ly
EMPLOYEE_ID: [9], Chris Canning
Closing all open resources…

Learn More About:

Conclusion

In this tutorial article, we discussed MongoDB JSON connectivity using JSON Connector. This combination is a powerful way to manage and execute queries for data stored in your database. And, if you want to learn more about the Connect in more detail, either of these two articles can help a great deal.

  1. JDBC Connector with MongoDB database
  2. Java connecting to MongoDB database examples

However, as a Developer, extracting complex data from a diverse set of data sources like Databases, CRMs, Project management Tools, Streaming Services, Marketing Platforms to your MongoDB Database, or maintaining the Connect can seem to be quite challenging. This is where a simpler alternative like Hevo can save your day!

Also, don’t forget to share your experience of establishing Connect in the comments section below!

Satyam Agrawal
CX Engineer

Satyam boasts over two years of adept troubleshooting and deliverable-oriented experience. His client-focused approach has enabled seamless data pipeline management for numerous SMEs and Enterprises. Proficient in Hevo’s ETL architecture and skilled in DBMS sources, he ensures smooth data movement for clients. Satyam leverages automated tools to extract and load data from various databases to warehouses, implementing SQL principles and API calls for day-to-day troubleshooting.