Docs Menu

Connect to MongoDB

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.

Note

If you run into issues on this step, 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.