Docs Menu

Get Started with the Java Driver

The Java driver is a synchronous API that you can use to interact with MongoDB from your Java application. This guide shows you how to create an application that uses the Java driver to connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster.

Tip

MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.

Follow this tutorial to connect a sample Java application to a MongoDB Atlas deployment. The tutorial includes the following sections:

If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.

Complete the following steps to install the Java driver and its dependencies in your development environment.

1

Before you begin this tutorial, ensure that you install the following dependencies:

Note

This tutorial shows how to install the Java driver by using Maven or Gradle in an IDE. If you do not use an IDE, visit Building Maven or Creating New Gradle Builds to learn how to set up your project.

2

In your IDE, create a new Maven or Gradle project. If you use Maven, add the following code to your pom.xml dependencies list:

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

If you use Gradle, add the following code to your build.gradle dependencies list:

dependencies {
implementation 'org.mongodb:mongodb-driver-sync:5.4.0'
}

After you configure your dependencies, ensure they are available to your project by running your dependency manager and refreshing the project in your IDE.

After you complete these steps, you have a new project and the driver dependencies installed.

You can create a free tier MongoDB deployment on MongoDB Atlas to store and manage your data. MongoDB Atlas hosts and manages your MongoDB database in the cloud.

1

Complete the Get Started with Atlas guide to set up a new Atlas account and a free tier MongoDB deployment. Ensure that you load sample data and add your IP address to the IP access list.

2

After you create your database user, save that user's username and password to a safe location for use in an upcoming step.

After you complete these steps, you have a new free tier MongoDB deployment on Atlas, database user credentials, and sample data loaded in your database.

You can connect to your MongoDB deployment by providing a connection URI, also called a connection string, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.

The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.

1

To retrieve your connection string for the deployment that you created in the previous step, log into your Atlas account and navigate to the Clusters section. Click the Connect button for your new deployment, as shown in the following screenshot:

The connect button in the clusters section of the Atlas UI

Then, proceed to the Connect your application section. Select "Java" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.

2

Click the button on the right of the connection string to copy it to your clipboard, as shown in the following screenshot:

The connection string copy button in the Atlas UI
3

Paste your connection string into a file in your preferred text editor and save this file to a safe location for later use. In your connection string, replace the <db_username> and <db_password> placeholders with your database user's username and password.

After completing these steps, you have a connection string that contains your database username and password.

After retrieving the connection string for your MongoDB Atlas deployment, you can connect to the deployment from your Java application and query the Atlas sample datasets.

1

In your project's base package directory, create a file called QuickStart.java. Copy and paste the following code into this file, which queries the movies collection in the sample_mflix database:

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;
public class QuickStart {
public static void main( String[] args ) {
// Replace the placeholder with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Document doc = collection.find(eq("title", "Back to the Future")).first();
if (doc != null) {
System.out.println(doc.toJson());
} else {
System.out.println("No matching documents found.");
}
}
}
}
2

Replace the <connection string uri> placeholder with the connection string that you copied from the Create a Connection String step of this guide.

3

Run your application in your IDE or your shell. Your output contains details about the retrieved movie document:

{
_id: ...,
plot: 'A young man is accidentally sent 30 years into the past...',
genres: [ 'Adventure', 'Comedy', 'Sci-Fi' ],
...
title: 'Back to the Future',
...
}

If you encounter an error or see no output, ensure that you specified the correct connection string and that you loaded the sample data.

Important

TLS v1.3 Connection Error

If your application generates an error that resembles the following code, you might need to update your JDK to the latest patch release:

javax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request

This exception is a known issue when using the TLS 1.3 protocol with some JDK versions. To resolve the error, update your JDK to one of the following versions, or a newer version:

  • JDK 11.0.7

  • JDK 13.0.3

  • JDK 14.0.2

After you complete these steps, you have a Java application that connects to your MongoDB deployment, runs a query on the sample data, and returns a matching document.

Congratulations on completing the tutorial!

Note

If you run into issues in this tutorial, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.

In this tutorial, you created a Java driver application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.

You can continue to develop your sample application by visiting the following guides: