Introduction


JDBC is a set of classes and interfaces written in Java that allows Java programs to access a database. This short How-to describes the quick way how to access MongoDB through a JDBC connection. MongoDB is a popular document-oriented NoSQL database from MongoDB, Inc.

Download driver package


At the time of writing, multiple JDBC drivers were available. I picked the latest "official" driver version 3.9.1, located here. The following 3 files should be downloaded:

In order to work with the driver, Java must be able to find it when called. In older versions of Java up to Version 8, we could simply place the driver files into the Java standard directory for extensions. For JRE, it used to be the $JAVA_HOME/jre/lib/ext directory.

Newer Java (e.g. 11) removed the extensions directory, and this requires adding the location of the JDBC driver to the Java classpath. An example is shown below.

Demonstration code how tro access a Mongo Database


The following example code JdbcTestMongoDB.java can be used to quickly access and test the JDBC connection. MongoDB uses the default port TCP-27017 for access.

vi JdbcTestMongoDB.java
// JdbcTestMongoDB.java
//
// compile: $ javac -cp ./jdbc/*:. JdbcTestMongoDB.java
// run: $ java -cp ./jdbc/*:. JdbcTestMongoDB

import com.mongodb.ConnectionString;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoException;
import java.util.logging.Logger;
import java.util.logging.Level;

public class JdbcTestMongoDB {
   public static void main(String[] args) {
      try {
         // Quieten down the default JDBC driver logging noise
         Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
         mongoLogger.setLevel(Level.SEVERE); // e.g. or Log.WARNING, etc.

         // Open a connection to the database. Using create() without
         // further arguments attempts to open a connection to localhost:27017
         // MongoClient mongoClient = MongoClients.create();
         // For non-default DB's the easiest way is to set a connnection string
         MongoClient mongoClient = MongoClients.create("mongodb://admin:test@localhost:27017/?authSource=admin");

         // Set the database schema to access
         MongoDatabase db = mongoClient.getDatabase("admin");

         // And return a list of all database collections
         for (String name : db.listCollectionNames()) {
            System.out.println(name);
         }
      }
      catch (MongoException e) {
         System.err.println (e);
         System.exit (-1);
      }
   }
}

Compile and test run


fm@susie:~> javac -cp ./jdbc/*:. JdbcTestMongoDB.java
fm@susie:~> java -cp ./jdbc/*:. JdbcTestMongoD
system.users
system.version

I tested it against MongoDB server version 3.6.3.

Additional Literature: MongoDB Driver 3.9 Documentation