MongoDB Java Integration: 12 Easy Steps

on Data Integration, Database Management Systems, Java, MongoDB, Tutorials • March 1st, 2022 • Write for Hevo

MongoDB Java | Hevo Data

This page provides a comprehensive overview of how you can get started with MongoDB and Java. In this post, you’ll learn how to connect your Java application to a MongoDB instance. Then you will perform some common MongoDB operations using the MongoDB Java driver. Read along to set up your MongoDB Java Integration today!

Table of Contents

What is MongoDB?

MongoDB is an open-source document database that has a wide range of applications. It can be used as an analytical database, transactional database, search index, or data warehouse, among other use cases. MongoDB has a flexible schema that provides support for full indexing, replication, JSON-like storage, and a non-structured query language. 

The key MongoDB concepts are:

  • Id: An id is a field name that is used to represent a unique object in MongoDB. It can be created explicitly by the user or implicitly by the MongoDB server. 
  • Collection: It is a bucket that stores a group of MongoDB documents. It falls under a database in the hierarchy.
  • Database: This is the topmost level of data organization in a MongoDB instance. The database stores collections and a MongoDB instance can contain many databases.
  • Document: The records stored in a MongoDB collection are called documents. They contain keys and values. The values can be strings, integers, booleans, dates as well as other embedded documents.
  • Field: This refers to the key/value pair in a document.

Key Features of MongoDB

MongoDB has several extraordinary capabilities that make it widely usable and popular. Let’s take a look at MongoDB’s top technical features:

Supports Adhoc Queries

One of the biggest benefits that make MongoDB stand out is its performance when handling ad hoc queries on data that are usually updated in real-time. MongoDB can perform field searches, range searches, as well as regular expression queries.

Indexing

Indexing is an important feature of a Database for improving search speed and performance of search queries. Without indexing, a database would be forced to scan documents one by one to select those that match the query which would be inefficient. However, if each query has an appropriate index, user requests can be quickly executed by the server. With MongoDB indexing is possible with any field or key, in a document sustaining complex access patterns to datasets.

Schema-Less Database

Classic relational databases use a schema to define every functional element, including tables, rows views, indexes, and relationships. In MongoDB, one collection maintains different documents. It has no schema so there can be numerous documents in a collection, having distinct keys, and these keys might be unique. A schemaless database, like MongoDB, is more flexible as it does not carry these up-front constraints, mapping to a more ‘natural’ database.

To learn more about MongoDB, visit here.

What is Java?

Java is a popular programming language that’s mostly used for server-side development as well as mobile app development. In its design, Java is an object-oriented language which simply means that all data and methods are represented as classes and objects.

Java can be both compiled or interpreted meaning that the translation of the Java code to bytecode or binary format can be done using a compiler or interpreter. Since it’s a compiled language, it’s very fast at runtime and also very easy to debug.

Some top Java use cases include developing:

  • Android applications
  • Desktop GUI applications
  • Web applications
  • Scientific applications 
  • Financial sector server-side applications
  • Embedded Systems

Key Features of Java

The following features give Java an edge over other Programming Languages:

  • Object-Oriented: Java Programming Language treats everything as an object. It can easily map real-world scenarios into code by treating individual entities as objects. 
  • Platform Independent: Unlike programming languages ​​like C and C ++, Java is not compiled in a platform-specific machine. It produces a platform-independent Byte Code that is distributed over the internet and is interpreted by the Java Virtual Machine (JVM) installed on any system. 
  • Security: With the security feature of Java Programming Language, it allows you to develop tamper-proof and virus-free systems. Also, it uses Public-key cryptography-based authentication techniques to keep your code and data safe.
  • Portable: Java is an architecture-independent Programming Language. So it is easy to port a code written in Java Programming Language to different processors.
  • Robust: Java is a Programming Language that strives to eliminate error-prone instances using compile-time error checking and runtime checking.

To learn more about Java Programming Language, visit here.

Simplify your Data Analysis with Hevo’s No-code Data Pipeline

Hevo Data, an Automated No-code Data Pipeline helps to Load Data from any data source such as Databases, SaaS applications, Cloud Storage, SDK,s, and Streaming Services and simplifies the ETL process. It supports 100+ data sources like MongoDB and loads the data onto the desired Data Warehouse, enriches the data, and transforms it into an analysis-ready form without writing a single line of code.

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Its fault-tolerant and scalable architecture ensure that the data is handled in a secure, consistent manner with zero data loss and supports different forms of data. The solutions provided are consistent and work with different Business Intelligence (BI) tools as well.

Get Started with Hevo for Free

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
Load Data to BigQuery for Free

What are the steps to set up MongoDB Java Integration?

Hopefully, by now, you have acquired some basic understanding of MongoDB and Java as well as why they’re used in application development. Now let’s dive in and take a look at the steps using which you can set up MongoDB Java integration:

Step 1: Install the OpenJDK package

To follow along with the MongoDB Java setup, you’ll first need to prepare your local machine for Java development. To do so, you need to first install the OpenJDK 8 (Open Java Development Kit) package.

1) Linux

If you’re on Debian or Ubuntu, open your command line and run the following command:

$ sudo apt-get install openjdk-8-jdk

For CentOS, Red Hat, Oracle, Fedora, and other similar Linux distributions use the following command:

$ su -c "yum install java-1.8.0-openjdk-devel"

2) macOS

If you’re on macOS use the following command:

% brew install openjdk@8

Then create a symbolic link so that the Java wrapper can find it:

% sudo ln -sfn /usr/local/opt/openjdk@8/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-8.jdk 

3) Windows

  • Download the MSI-based installer from this link.
  • Extract the zip files to a folder.
  • Run the OpenJDK 8 for Windows installer.
  • Follow the on-screen prompts to install.

Step 2: Set the JAVA_HOME Environment variable

Once your JDK is in place, you need to install the Java environment to proceed with your MongoDB Java integration.

1) Linux

  1. Open your terminal and type:
sudo nano /etc/profile
  1. Then go to the end of the file and type:
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/bin/java
export PATH=$JAVA_HOME/bin:$PATH
  1. Save the file and exit (ctrl+o, ctrl+x).

2) macOS

  1. Open your terminal and type:
emacs .profile
  1. Then go to the end of the file and type:
JAVA_HOME=/Library/Java/Home
export JAVA_HOME;
  1. Save and exit (ctrl-x, ctrl-s; ctrl-x, ctrl-c).

3) Windows

To set the environment variable on your Windows machine, open the Command Prompt with admin privileges and run the following command:

setx -m JAVA_HOME "C:Progra~1Javajdk1.8.0_XX"

Next, restart the Command Prompt to reload the environment variables. Run the following command to check whether the path has been added: 

echo %JAVA_HOME%

Step 3: Install MongoDB

Once you are done with the Java part of the MongoDB Java integration, it time to install MongoDB and its tools.

1) Linux

  1. Open a terminal and issue the following command to import the MongoDB public key from the package management system:
wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
  1. Next create a list file by issuing the following command:
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
  1. Refresh the package database.
sudo apt-get update
  1. Run the following command to install MongoDB:
sudo apt-get install -y mongodb-org
  1. Start MongoDB:
sudo systemctl start mongod
  1. Verify that MongoDB is running:
sudo systemctl status mongod

MongoDB should be running on port 27017.

The instructions above were tested on Ubuntu 20.0. You can get the installation instructions for other Linux distributions from the following link.

2) macOS

  1. Issue the following command to download the Homebrew formula for MongoDB:
brew tap mongodb/brew
  1. Install MongoDB using the following command:
brew install mongodb-community@5.0
  1. For macOS computers running Intel processors, start MongoDB using the following command:
mongod --config /usr/local/etc/mongod.conf --fork
  1. For macOS computers running M1 processors, use the following command:
mongod --config /opt/homebrew/etc/mongod.conf --fork

3) Windows

  1. Download the MongoDB MSI-based installer from this link.
  1. Run the installer by double-clicking the .msi file.
  1. Follow the on-screen prompts to install.

Step 4: Install an IDE or Editor

To run the examples given in this blog, we recommend that you use an integrated development environment (IDE). This is because it makes it much more convenient for you to configure Maven or Gradle when building and running your Java project.

Below you’ll find a list of some popular editors used to develop Java apps and will suit your MongoDB Java integration:

  • Atom by GitHub
  • IntelliJ IDEA by JetBrains
  • Visual Studio Code by Microsoft
  • Eclipse by Eclipse Foundation

These IDEs offer useful features such as syntax highlighting, code completion, fully integrated debugging capabilities, and much more.

Step 5: Setup a New Java Project

Using your favorite IDE, create a new Maven or Gradle project. If you’re using Maven, you should get the following folder structure:

java-quick-start/
├── pom.xml
└── src
    └── main
        └── java
            └── com
                └── mongodb
                    └── quickstart

If you are using Gradle, you should have the following folder structure:

├── build.gradle
└── src
    └── main
        ├── java
            └──

Step 6: Install the MongoDB Client Library for Java

The MongoDB client library for Java lets you connect to and communicate with your MongoDB instance from a Java application.

If you are using Maven, add the MongoDB Java client library to your dependencies list in your pom.xml file.

<dependencies>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver-sync</artifactId>
        <version>4.4.1</version>
    </dependency>
</dependencies>

Your pom.xml file should now look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mongodb</groupId>
    <artifactId>java-quick-start</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven-compiler-plugin.source>8</maven-compiler-plugin.source>
        <maven-compiler-plugin.target>8</maven-compiler-plugin.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mongodb-driver-sync.version>4.4.1</mongodb-driver-sync.version>
        <maven-compiler-plugin.version>3.10.0</maven-compiler-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>${mongodb-driver-sync.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven-compiler-plugin.source}</source>
                    <target>${maven-compiler-plugin.target}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

If you’re using Gradle, add the following code snippet to your build.gradle dependencies list for your MongoDB Java integration:

dependencies {
  compile 'org.mongodb:mongodb-driver-sync:4.4.1'
}

Your build.gradle file should resemble the following file:

plugins {
    id 'base'
}

import org.gradle.distribution.DownloadGradle

version = '0.1'

dependencies {
  compile 'org.mongodb:mongodb-driver-sync:4.4.1'
}


tasks.register('downloadGradle', DownloadGradle) {
    description = 'Downloads the Gradle distribution with a given version.'
    gradleVersion = '4.6'
}

tasks.register('createCustomGradleDistribution', Zip) {
    description = 'Builds custom Gradle distribution and bundles initialization scripts.'

    dependsOn downloadGradle

    def projectVersion = project.version
    archiveFileName = downloadGradle.gradleVersion.map { gradleVersion ->
        "mycompany-gradle-${gradleVersion}-${projectVersion}-bin.zip"
    }

    from zipTree(downloadGradle.destinationFile)

    from('src/init.d') {
        into "${downloadGradle.distributionNameBase.get()}/init.d"
    }
}

Step 7: Using the MongoDB Java Client Library

To use the MongoDB Java client library, create a file that will contain your application inside the base package directory of your project. You can name it App.java

Add the following import statements to initialize the library:

import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

Step 8: Create a MongoDB Collection

With that out of the way, it’s now time that your MongoDB Java integration interacts with the database. Let’s first start by creating a collection. You can create a MongoDB collection by specifying the target database using the getDatabase() method and then invoking the createCollection() method of the com.mongodb.client.MongoDatabase interface. This method accepts a literal string value with the name of the collection. If the database does not exist, MongoDB will create it implicitly.

The following code snippet creates a collection in a MongoDB database:

import java.util.Arrays;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertOneResult;

public class CreateCollection {
    public static void main(String[] args) {

        String uri = "mongodb://localhost:27017";
        // Create a MongoDB Client
        MongoClient mongoClient = MongoClients.create(uri));
       // Create a MongoDB database
        MongoDatabase database = mongoClient.getDatabase("usersDB");
        // Create a MongoDB Collection
        MongoCollection<Document> collection = database.createCollection("users");
                System.out.println("Collection Created Successfully!");
            }
}

Step 9: Create Documents

The following snippet uses the insertOne() method to insert a document into the user’s collection that you created in the previous step. If the database or collection does not exist, MongoDB will create both.

{“username”: “vitali@30”, “phonenumber”: 2501345876, “email”: “vitaly12@gsuite.com”}

import java.util.Arrays;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertOneResult;

public class InsertOne {
    public static void main(String[] args) {
        
        String uri = "mongodb://localhost:27017";

        try (MongoClient mongoClient = MongoClients.create(uri)) {

            MongoDatabase database = mongoClient.getDatabase("usersDB");
            MongoCollection<Document> collection = database.getCollection("users");

            try {
                InsertOneResult result = collection.insertOne(new Document()
                        .append("_id", new ObjectId())
                        .append("username", "vitali@30")
                        .append("phonenumber", 2501345876)

                        .append("email", "vitaly12@gsuite.com)

);

                System.out.println("Success! Inserted document id: " + result.getInsertedId());
            } catch (MongoException me) {
                System.err.println("Unable to insert due to an error: " + me);
            }
        }
    }
}

It is also possible to insert multiple documents into a collection at one go by invoking the insertMany() method. To insert multiple documents, you have to add them to a List and pass that List as an array. The following code snippet illustrates how you can use the insertMany() method to achieve this.

import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.InsertManyResult;

public class InsertMany {

    public static void main(String[] args) {
        String uri = "mongodb://localhost:27017";

        try (MongoClient mongoClient = MongoClients.create(uri)) {

            MongoDatabase database = mongoClient.getDatabase("usersDB");
            MongoCollection<Document> collection = database.getCollection("users");

            List<Document> userList = Arrays.asList(
                    new Document().append("username", "owen hart"),
                    new Document().append("username", "jack grealish"));

            try {
                InsertManyResult result = collection.insertMany(userList);

                System.out.println("Inserted document ids: " + result.getInsertedIds());
            } catch (MongoException me) {
                System.err.println("Unable to insert due to an error: " + me);
            }
        }
    }
}

Step 10: Query Documents

Working with your MongoDB Java integration, you can retrieve documents in a collection by invoking the find() method. This method returns an iterable object that contains all the documents in a collection:

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;

public class Find {
    public static void main( String[] args ) {

        String uri = "mongodb://localhost:27017";

        try (MongoClient mongoClient = MongoClients.create(uri)) {

            MongoDatabase database = mongoClient.getDatabase("usersDB");
            MongoCollection<Document> collection = database.getCollection("users");

            FindIterable<Document> iterDoc = collection.find();

            Iterator it = iterDoc.iterator();
            while (it.hasNext()) {
             System.out.println(doc.it.next());
        }

        }
    }
}

Step 11: Update Documents

Updates in a MongoDB database can be done using the updateOne() method of the Updates class. In the following example, you will be updating the value of the phone number and adding an address to the document that matches the username “vitali@30”.

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;

public class UpdateOne {

    public static void main(String[] args) {
   
        String uri = "mongodb://localhost:27017";

        try (MongoClient mongoClient = MongoClients.create(uri)) {

            MongoDatabase database = mongoClient.getDatabase("usersDB");
            MongoCollection<Document> collection = database.getCollection("users");

            Document query = new Document().append("username",  "vitali@30");

            Bson updates = Updates.combine(
                    Updates.set("phonenumber", 010154257),
                    Updates.addToSet("address", "666, 5th Avenue, NYC"));

            UpdateOptions options = new UpdateOptions().upsert(true);

            try {
                UpdateResult result = collection.updateOne(query, updates, options);

                System.out.println("Modified document count: " + result.getModifiedCount());

                System.out.println("Upserted id: " + result.getUpsertedId()); // only contains a value when an upsert is performed
            } catch (MongoException me) {
                System.err.println("Unable to update due to an error: " + me);
            }
        }
    }
}

Step 12: Delete Documents

Once the MongoDB Java integration is set, you can still perform a delete operation on a document in a MongoDBcollection using the deleteOne() method. The method accepts a query filter that matches the document you want to delete.

The following code snippet will delete one user by using the eq() filter to identify a specific user with the username “vitali@30” from your MongoDB Java integration:

import static com.mongodb.client.model.Filters.eq;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;

public class DeleteOne {

    public static void main(String[] args) {

        String uri = "mongodb://localhost:27017";

        try (MongoClient mongoClient = MongoClients.create(uri)) {

            MongoDatabase database = mongoClient.getDatabase("usersDB");
            MongoCollection<Document> collection = database.getCollection("users");

            Bson query = eq("username", "vitali@30");

            try {
                DeleteResult result = collection.deleteOne(query);
                System.out.println("Deleted document count: " + result.getDeletedCount());
            } catch (MongoException me) {
                System.err.println("Unable to delete due to an error: " + me);
            }
        }
    }
}

That’s it! You can now set up your own MongoDB Java integration.

Conclusion

This article introduced you to MongoDB and Java programming language along with their key features. If you have successfully completed this guide, you should have a good idea of how to set up the MongoDB Java integration. You have covered the steps required to set up MongoDB and Java development environments on your PC or server. You also covered how to use the Java driver to connect to your MongoDB instance. Finally, you saw examples of how to write some simple MongoDB Java CRUD operations.

Visit our Website to Explore Hevo

MongoDB is a great tool for storing your business data. However, at times, you need to transfer this data to a Data Warehouse for further analysis. Building an in-house solution for this process could be an expensive and time-consuming task. Hevo Data, on the other hand, offers a No-code Data Pipeline that can automate your data transfer process, hence allowing you to focus on other aspects of your business like Analytics, Customer Management, etc. This platform allows you to transfer data from 100+ sources like MongoDB to Cloud-based Data Warehouses like Snowflake, Google BigQuery, Amazon Redshift, etc. It will provide you with a hassle-free experience and make your work life much easier.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. 

Share your views on MongoDB Java integration in the comments section!

No Code Data Pipeline For Your Data Warehouse