Connecting MongoDB JDBC in Simple Steps

Photo of Jim Kutz
Jim Kutz
December 13, 2025

Summarize this article with:

✨ AI Generated Summary

You probably already have MongoDB humming along, storing rich JSON-like documents, yet every Java library, BI dashboard, or legacy script in your stack still speaks SQL and expects a JDBC endpoint. That mismatch turns a simple reporting request into a weekend plumbing project.

A MongoDB JDBC driver closes the gap by translating SQL calls into MongoDB queries on the fly, so collections appear as familiar tables. Once the driver JAR sits on your classpath, you can open a connection, issue SELECT * FROM orders LIMIT 10, and get results without rewriting code or exporting data.

This guide covers the practical four-step path: installing the driver, crafting a bullet-proof connection URL, testing queries from Java, and wiring the same connection into tools like DBeaver or Tableau. When connection errors pop up, you'll know exactly where to look and how to fix them.

TL;DR: Connecting MongoDB Through JDBC

  • A MongoDB JDBC driver lets SQL-based tools query MongoDB by translating SQL into MongoDB queries on the fly.
  • You’ll need a running MongoDB instance, credentials, the correct JDBC driver JAR, a valid connection URL, and a Java/BI tool that supports JDBC.
  • Connection issues usually stem from missing drivers, wrong authSource, IP allow-list problems, or TLS misconfiguration.
  • For production pipelines, JDBC becomes brittle—tools like Airbyte provide automated change detection, schema evolution handling, and warehouse syncs without custom scripts.

What Do You Need Before Using MongoDB With JDBC?

Get these basics locked down before bringing JDBC into the picture:

  • A running MongoDB instance, either localhost:27017 for testing or an Atlas cluster for production, with host, port, and default database details ready.
  • Valid credentials including username, password, and authentication database (often admin). Error 18 appears when the user is defined in a different auth DB.
  • The correct JDBC driver JAR, either the official Atlas SQL JDBC driver or a vendor option like CData, placed where your application or BI tool can load it.
  • A Java runtime (JDK 8 or newer) on the system path, since older JVMs cannot load modern JDBC 4 drivers.
  • An SQL or BI client such as DBeaver or Tableau to validate connectivity before embedding connection logic in code.
  • A driver version that matches your deployment environment and feature set.
  • A whitelisted IP address for Atlas clusters to avoid timeouts during connection attempts.

1. How to Install the MongoDB JDBC Driver

Installing the JDBC driver requires placing the JAR file in an accessible location and ensuring Java recognizes it properly.

Download the appropriate JAR by getting the shaded "with dependencies" build of MongoDB's official Java (not JDBC) driver from their official driver page. This gives you a single file to manage.

Add it to your classpath through your preferred method. For Maven projects, to use the official MongoDB Java driver, include this dependency:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongodb-driver-sync</artifactId>
  <version>VERSION</version> <!-- check site for current version -->
</dependency>

Note: If you specifically need JDBC support for MongoDB, consult third-party JDBC driver vendors for the appropriate Maven coordinates.

For plain JAR projects or BI tools, copy the downloaded JAR into the tool's driver directory or your project's lib folder. Missing JARs cause "No suitable driver" errors.

Load the driver when necessary. Modern JDBC 4 drivers self-register on Java 8+, but older servers or explicit loading scenarios may require:

Class.forName("com.mongodb.jdbc.MongoDriver");

This class name remains consistent across recent releases — check the driver's README to confirm.

With these components configured, any Java program or SQL/BI tool supporting JDBC can connect to your MongoDB instance.

2. How to Build the MongoDB JDBC Connection URL

Building a proper JDBC URL requires understanding the connection pattern and configuring authentication and optional parameters correctly.

Basic Connection URL Format

Every MongoDB JDBC connection starts with the skeleton: 

jdbc:mongodb://host:port/database. This pattern mirrors the native MongoDB URI with a jdbc: prefix for Java's DriverManager recognition. A minimal local development URL looks like:

jdbc:mongodb://localhost:27017/myapp

You can omit :27017 for default ports. The database name after the final slash becomes the default for subsequent queries.

Authentication Parameters

Embed credentials directly using: jdbc:mongodb://user:pass@host:27017/database. When passwords contain reserved characters, percent-encode them ( @ becomes %40, / becomes %2F)to avoid parsing failures. 

For cleaner URLs, pass credentials through a Properties object:

Properties props = new Properties();
props.put("user", "reportUser");
props.put("password", "pe@ce%2Flog");
Connection conn = DriverManager.getConnection("jdbc:mongodb://localhost:27017/sales", props);

If your user exists in a different database, append ?authSource=admin to avoid authentication errors.

Optional Parameters

Fine-tune behavior by chaining query-string options. Key parameters include ssl=true (or tls=true) for encrypted traffic, which is mandatory for Atlas clusters, as well as connectTimeoutMS=10000 to abort failed attempts after ten seconds. You can also use readPreference=secondaryPreferred for routing reads away from the primary, and replicaSet=myReplSet to target specific replica sets.

Complete examples demonstrate the flexibility:

// Local, no auth
jdbc:mongodb://localhost/myapp
// On-premises replica set with authentication
jdbc:mongodb://dbUser:pe%40ss@mongo1:27017,mongo2:27017/sales?authSource=admin&replicaSet=prodReplSet
// Atlas production string
jdbc:mongodb://analyticsUser:enc%40ded@atlas-cluster.mongo.net/federatedDb?ssl=true&readPreference=secondaryPreferred&connectTimeoutMS=10000

3. How to Test MongoDB JDBC From a Java Application

Testing your JDBC setup through Java code verifies that the driver loads correctly, your connection URL works, and credentials authenticate successfully.

Start by ensuring driver availability. Most JDBC 4 drivers register automatically, but explicit loading works for older JVMs or specific application servers:

Class.forName("com.mongodb.jdbc.MongoDriver");   // falls back gracefully if already registered

This call is harmless when auto-registration is active and guarantees driver readiness.

Next, construct your JDBC URL and establish the connection. Using a Properties object keeps URLs clean and prevents password exposure in logs:

String url = "jdbc:mongodb://localhost:27017/testdb?authSource=admin";
Properties props = new Properties();
props.put("user", "myUser");
props.put("password", "myPassword");
try (Connection conn = DriverManager.getConnection(url, props)) {
  // run queries here
}

Once connected, treat collections like relational tables. This example selects five documents and prints the first column to verify the SQL layer:

Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM myCollection LIMIT 5");
while (rs.next()) {
  System.out.println(rs.getString(1));
}

Always close ResultSet, Statement, and Connection objects using try-with-resources. Unclosed handles accumulate quickly and trigger "too many connections" errors. These few lines confirm your driver, URL, network path, and credentials all function properly.

4. How to Connect MongoDB via JDBC From a SQL/BI Tool

SQL clients and BI platforms can access MongoDB through JDBC once you configure the driver and connection properly.

Adding the JDBC Driver

Place the driver file where your tool expects it. In DBeaver, navigate to "Database → Driver Manager," click "New," and browse to your downloaded JAR. The wizard automatically detects the driver class. Tools like Sisense provide similar dialogs under their MongoDB connector settings for direct JAR uploads.

Creating the Connection

Establish a new connection referencing your driver. Paste a URL like jdbc:mongodb://host:27017/sales or your Atlas connection string, then fill in username and password fields. For credentials stored in the admin database, append ?authSource=admin. Omitting this parameter causes "Authentication failed (error 18)" messages.

Testing and Querying

Use the "Test Connection" button available in most tools. A successful test confirms the driver loaded, network connectivity works, credentials are valid, and the database is reachable. Failed tests usually indicate incorrect JAR paths, malformed URLs, or IP restrictions.

Once connected, collections appear in the object browser as standard tables. Run SELECT * FROM customers LIMIT 10; to watch BSON documents transform into tabular data. Your BI tool now translates SQL into MongoDB queries in real time.

How to Fix Common MongoDB JDBC Connection Issues?

Most JDBC failures stem from four common issues: missing drivers, authentication problems, network timeouts, and TLS configuration errors.

Driver Not Found Errors

"No suitable driver" or ClassNotFoundException indicates the JDBC JAR isn't on your runtime classpath or uses an incorrect driver class name. Add the JAR to your project or BI tool, then verify the class name matches vendor documentation. URL mismatches like jdbc:mongo:// versus jdbc:mongodb:// trigger identical errors.

Authentication Failures

Error 18 AuthenticationFailed points to credential issues. Confirm your user works in mongosh, then verify your connection string includes the correct authSource. Community discussions frequently show connections failing until ?authSource=admin was added. Special characters in passwords need percent-encoding to avoid silent mismatches.

Connection Timeouts

Timeouts typically indicate firewall issues or missing IP allow-list entries. Test basic reachability with ping or telnet. For Atlas projects, ensure your client IP is whitelisted in Network Access settings. Increasing connectTimeoutMS gives slow networks more time before failing.

TLS Certificate Errors

TLS errors occur when servers require encryption but your URL lacks ssl=true, or when clients cannot validate certificates. Adding ssl=true (or tls=true) to your JDBC URL and importing the server's CA certificate resolves most handshake problems.

Error Message Likely Cause Quick Fix
No suitable driver found Driver JAR missing or wrong URL prefix Add JAR to classpath and use the jdbc:mongodb:// scheme
Authentication failed (code 18) Wrong authSource or bad credentials Verify user in shell, then add ?authSource=admin
Connection timeout Firewall or IP not whitelisted Test network, whitelist IP for Atlas, or increase connectTimeoutMS
SSL handshake failed TLS required but not enabled or untrusted cert Append ssl=true and import the server's CA certificate

How Can You Move Beyond JDBC and Sync MongoDB Data Automatically?

JDBC provides SQL access to MongoDB collections but places significant operational burden on your team. You must write custom scripts for incremental loads, maintain cron jobs that break when collections change, and debug weekend failures during schema evolution. Data teams report spending half of their time maintaining these homegrown pipelines instead of building business value.

Airbyte's purpose-built MongoDB connector eliminates this maintenance overhead. It captures change streams automatically, tracks schema evolution without breaking pipelines, and syncs only new or modified documents to warehouses like Snowflake, BigQuery, or Databricks. With 600+ connectors and visual scheduling, your team focuses on analytics while Airbyte handles data movement reliably. 

Connect MongoDB to your data warehouse without writing custom scripts. Try Airbyte and sync your first collection with 600+ pre-built connectors.

Frequently Asked Questions

Can I use any MongoDB driver as a JDBC driver?

No. The official MongoDB Java driver is not a JDBC driver. For JDBC use cases, you must use a JDBC-compliant driver from MongoDB Atlas SQL, CData, Progress/DataDirect, or similar vendors.

Why does my MongoDB JDBC connection fail with “Authentication Failed (Error 18)”?

This almost always means the user is defined in a different authentication database. Add ?authSource=admin (or the correct database) to your JDBC URL.

Can I use JDBC for high-volume production syncs?

Not reliably. JDBC works for BI tools and basic SQL access, but it lacks incremental sync, schema evolution handling, and automation. Tools like Airbyte are built for production-grade movement of MongoDB data.

Why does my JDBC connection timeout when connecting to MongoDB Atlas?

Atlas requires IP allow-listing. Add your client IP in the Atlas Network Access panel. Also ensure ssl=true is included in your JDBC URL.

Limitless data movement with free Alpha and Beta connectors
Introducing: our Free Connector Program
The data movement infrastructure for the modern data teams.
Try a 30-day free trial
Photo of Jim Kutz