Skip to content

Building JAVA MongoDB Driver

linuxonz edited this page Nov 28, 2024 · 50 revisions

Building MongoDB Java Driver

Below versions of MongoDB Java Driver are available in respective distributions at the time of creation of these build instructions:

  • Ubuntu (20.04, 22.04, 24.04, 24.10 ) have 3.6.3

General Notes:

  • When following the steps below please use a standard permission user unless otherwise specified.
  • A directory /<source_root>/ will be referred to in these instructions, this is a temporary writable directory anywhere you'd like to place it.

MongoDB Java Driver Jars are available and can be downloaded from here. Refer to instructions here for installation and usage of this driver. To use these Jars, Java needs to be installed on mentioned distributions.

Note: MongoDB Java Driver (v5.2.1) was verified at the time of creation of these instructions.

1. Install Dependencies

  • RHEL (8.8, 8.10, 9.2, 9.4)

    sudo yum install -y tar wget curl
  • SLES (15 SP5, 15 SP6)

    sudo zypper install -y wget tar curl gawk
  • Ubuntu (20.04, 22.04, 24.04. 24.10)

    sudo apt-get update
    sudo apt-get install -y tar wget curl 

2. Install Java

  • With IBM Semeru Runtime (previously known as AdoptOpenJDK openj9).

    • Download and install IBM Semeru Runtime (Java 11, Java 17 or Java 21) from here.
  • With Eclipse Adoptium Temurin Runtime (previously known as AdoptOpenJDK hotspot)

    • Download and install Eclipse Adoptium Temurin Runtime (Java 11, Java 17 or Java 21) from here.
  • With OpenJDK 11

    • RHEL (8.8, 8.10, 9.2, 9.4)
      sudo yum install -y java-11-openjdk
    • SLES (15 SP5, 15 SP6)
      sudo zypper install -y java-11-openjdk-devel
    • Ubuntu (20.04, 22.04, 24.04, 24.10)
      sudo apt-get install -y openjdk-11-jre
  • With OpenJDK 17

    • RHEL (8.8, 8.10, 9.2, 9.4)
      sudo yum install -y java-17-openjdk 
    • SLES (15 SP5, 15 SP6)
      sudo zypper install -y java-17-openjdk-devel
    • Ubuntu (20.04, 22.04, 24.04, 24.10)
      sudo apt-get install -y openjdk-17-jre 
  • With OpenJDK 21

    • RHEL (8.8, 8.10, 9.2, 9.4)
      sudo yum install -y java-21-openjdk
    • SLES 15 SP6
      sudo zypper install -y java-21-openjdk-devel 
    • Ubuntu (20.04, 22.04, 24.04, 24.10)
      sudo apt-get install -y openjdk-21-jre

Note: Versions (v11.0.21, v17.0.9 and v21.0.1.0) of IBM Semeru Runtime and (v11.0.21, v17.0.9, 21.0.2) of Adoptium Temurin Runtime were used at the time of creation of these instructions

3. Set environment variables

export JAVA_HOME=<path to Java installation directory>
export PATH=$JAVA_HOME/bin:$PATH

4. Basic validation test

The example code section given below is used to perform a basic test to ensure that the MongoDB Java Driver is working as expected, and can connect to, modify and query a MongoDB server. Instructions to install MongoDB and MongoDB Shell (mongosh) can be found on their official website here.

4.1 Start MongoDB

To run this test, MongoDB must be running on the default port, 27017. The following commands are an example of how to start a MongoDB server and then connect to it with the client shell.

Issue the following commands to start a MongoDB server:

sudo mkdir -p /var/lib/mongo
sudo mkdir -p /var/log/mongodb
sudo mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --bind_ip_all --fork

Issue the following command to check if the MongoDB Server is up, connect to it with the MongoDB shell (mongosh):

mongosh --host <hostname or IP address> --port 27017

The output should be similar to:

Current Mongosh Log ID:	61f7d8f084722a405ed097ea
Connecting to:		mongodb://<hostname or IP address>:27017/?directConnection=true&appName=mongosh+1.1.9
Using MongoDB:		5.0.5
Using Mongosh:		1.1.9
...
test>

4.2 Create test program

Create a file named test.java with the content shown below. This code connects to a MongoDB server, inserts some documents and then queries the database to read them back and display them.
Note: If you are connecting to a remote server, you need to substitute the localhost with the hostname or IP address of the MongoDB server.

import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

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

        String server_name="localhost";
        String database_name="ibm_test_db";
        String collection_name="mongodb_java_driver";

        MongoClient mongoClient = MongoClients.create("mongodb://"+server_name+":27017");
        MongoDatabase database = mongoClient.getDatabase(database_name);
        MongoCollection<Document> collection = database.getCollection(collection_name);

        collection.drop();

        Document doc = new Document("company", "IBM")
            .append("MongoDB Driver", new Document("language", "Java").append("version", "5.2.1"));
        collection.insertOne(doc);

        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; i < 3; i++) {
            documents.add(new Document("line", i));
        }
        collection.insertMany(documents);

        Document myDoc = collection.find().first();
        System.out.println(myDoc.toJson());
        MongoCursor<Document> cursor = collection.find().iterator();
        try {
            cursor.next();
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }
    }
}

4.3 Compile and run the test program

#Set Java classpath
export CLASSPATH=<Path to mongodb-driver-sync jar>:<Path to mongodb-driver-core jar>:<Path to bson jar>:.
javac -verbose test.java
java test

Executing the test program should produce output similar to this (the Object Ids will vary, but typically will be consecutive):

[main] INFO org.mongodb.driver.connection - Opened connection [connectionId{localValue:3, serverValue:592}] to localhost:27017
{"_id": {"$oid": "62191b78059ab161569b1b3b"}, "company": "IBM", "MongoDB Driver": {"language": "Java", "version": "5.2.1"}}
{"_id": {"$oid": "62191b78059ab161569b1b3c"}, "line": 0}
{"_id": {"$oid": "62191b78059ab161569b1b3d"}, "line": 1}
{"_id": {"$oid": "62191b78059ab161569b1b3e"}, "line": 2}

Note: If you are getting SLF4J warning, add SLF4J to your classpath to see missing logs.

#Set classpath
export CLASSPATH=<Path to mongodb-driver-sync jar>:<Path to mongodb-driver-core jar>:<Path to bson jar>:<Path to slf4j-api jar>:<Path to slf4j-simple jar>

References:

Clone this wiki locally