Docs Menu

Quick Start

On this page

This guide shows you how to create an application that uses the Java driver to connect to a MongoDB Atlas cluster. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official MongoDB drivers.

The Java driver lets you connect to and communicate with MongoDB clusters from a Java application.

MongoDB Atlas is a fully-managed cloud database service that hosts your data on MongoDB clusters. In this guide, we show you how to get started with your own free (no credit card required) cluster.

Consult the following steps to connect your Java application with a MongoDB Atlas cluster.

Make sure that your system has JDK 8 or later installed. For more information on how to check your version of Java and install the JDK, see the Oracle Overview of JDK Installation documentation.

This guide shows you how add the MongoDB Java driver dependencies using Maven or Gradle. We recommend that you use an integrated development environment (IDE) such as Intellij IDEA or Eclipse IDE make it more convenient to configure Maven or Gradle to build and run your project.

If you are not using an IDE, see Building Maven or Creating New Gradle Builds for more information on how to set up your project.

If you are using Maven, add the following to your pom.xml dependencies list:

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

If you are using Gradle, add the following to your build.gradle dependencies list:

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

Once you configure your dependencies, ensure they are available to your project which may require running your dependency manager and refreshing the project in your IDE.

After setting up your Java project dependencies, create a MongoDB cluster where you can store and manage your data. Complete the Get Started with Atlas guide to set up a new Atlas account, create and launch a free tier MongoDB cluster, load datasets, and interact with the data.

After completing the steps in the Atlas guide, you should have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster.

In this step, we create and run an application that uses the MongoDB Java driver to connect to your MongoDB cluster and run a query on the sample data.

We pass instructions to the driver on how to connect to your MongoDB cluster in a string called the connection string. This string includes information on the hostname or IP address and port of your cluster, authentication mechanism, user credentials when applicable, and other connection options.

If you are connecting to an instance or cluster that is not hosted by Atlas, see Other Ways to Connect to MongoDB for instructions on how to format your connection string.

To retrieve your connection string for the cluster and user you created in the previous step, log into your Atlas account and navigate to the Clusters section and click the Connect button for the cluster that you want to connect to as shown below.

Atlas Connection GUI cluster selection screen

Proceed to the Connect Your Application step and select the Java driver. Select "4.1 or Later" for the version. Click the Copy icon to copy the connection string to your clipboard as shown below.

Atlas Connection GUI connection string screen

Save your Atlas connection string in a safe location that you can access for the next step.

Next, create a file to contain your application called QuickStart.java in the base package directory of your project. Use the following sample code to run a query on your sample dataset in MongoDB Atlas, replacing the value of the uri variable with your MongoDB Atlas connection string. Ensure you replace the "<password>" section of the connection string with the password you created for your user that has atlasAdmin permissions:

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 static void main( String[] args ) {
// Replace the uri string 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();
System.out.println(doc.toJson());
}
}

When you run the QuickStart class, it should output the details of the movie from the sample dataset which will look something like this:

{
_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 receive no output or an error, check whether you included the proper connection string in your Java class, and whether you loaded the sample dataset into your MongoDB Atlas cluster.

Important
Known connection issue when using TLS v1.3

If you encounter an error connecting to your MongoDB instance or cluster that resembles the following while running your application, you may 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 specific versions of JDK, but was fixed for the following releases:

  • JDK 11.0.7
  • JDK 13.0.3
  • JDK 14.0.2

To resolve this error, update your JDK to one of the preceding patch versions or a newer one.

After completing this step, you should have a working application that uses the Java driver to connect to your MongoDB cluster, run a query on the sample data, and print out the result.

In the previous section, you ran a query on a sample collection to retrieve data in the map-like class Document. In this section, you can learn to use your own Plain Old Java Object (POJO) to store and retrieve data from MongoDB.

Create a file called Movie.java in the base package directory of your project and add the following code for a class that includes the following fields, setters, and getters:

public class Movie {
String plot;
List<String> genres;
String title;
public String getPlot() {
return plot;
}
public void setPlot(String plot) {
this.plot = plot;
}
public List<String> getGenres() {
return genres;
}
public void setGenres(List<String> genres) {
this.genres = genres;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "Movie [\n plot=" + plot + ",\n genres=" + genres + ",\n title=" + title + "\n]";
}
}

Create a new file QuickStartPojoExample.java in the same package directory as your Movie file in your project. Use the following sample code to run a query on your sample dataset in MongoDB Atlas, replacing the value of the uri variable with your MongoDB Atlas connection string. Ensure you replace the "<password>" section of the connection string with the password you created for your user that has atlasAdmin permissions:

import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry;
import static com.mongodb.client.model.Filters.eq;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class QuickStartPojoExample {
public static void main(String[] args) {
CodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix").withCodecRegistry(pojoCodecRegistry);
MongoCollection<Movie> collection = database.getCollection("movies", Movie.class);
Movie movie = collection.find(eq("title", "Back to the Future")).first();
System.out.println(movie);
}
}
}

When you run the QuickStartPojoExample class, it should output the details of the movie from the sample dataset which should look something like this:

Movie [
plot=A young man is accidentally sent 30 years into the past...,
genres=[Adventure, Comedy, Sci-Fi],
title=Back to the Future
]

If you receive no output or an error, check whether you included the proper connection string in your Java class, and whether you loaded the sample dataset into your MongoDB Atlas cluster.

See the following links for more information on using POJOs to store and retrieve data:

Learn how to read and modify data using the Java driver in our Fundamentals CRUD guide or how to perform common operations from our Usage Examples.

Give Feedback
© 2021 MongoDB, Inc.

About

  • Careers
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2021 MongoDB, Inc.