Lesson 2: Connecting to an Atlas Cluster in Java Applications / Learn

Connecting to an Atlas Cluster in Java Applications

In this lesson, you will install the MongoDB Java driver by using Maven, and then connect to your Atlas cluster.

To follow along with this lesson, open a new Maven project in IntelliJ. If you're using a different IDE or if you're using a text editor, the experience will be slightly different.

Install the MongoDB Java Driver


  1. Locate your pom.xml file.



2. In the file, insert the code for the dependency:

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

Note that we'll use the synchronous Java driver. Confirm that you're installing the latest version.


Obtain Your MongoDB Connection String


  1. Go to https://account.mongodb.com/account/login and log in to Atlas. The login page looks like the following: Once you're logged in, you will be taken to the Atlas dashboard for your current project. Click the Connect button.


    2. Once you're logged in, you will be taken to the Atlas dashboard for your current project. Click the Connect button.



    3. This window displays your connection options. Click the "Connect your application" button.



    4. This window contains the instructions for connecting your application. Click the copy icon to copy the connection string.


    Now you can use your connection string to connect to your Atlas cluster!


    Connect to Your Atlas Cluster


    1. Create a new file called Connection.java with the following code. This file uses your MongoDB connection string and the MongoClient to establish a connection with your Atlas cluster:
    package com.mongodb.quickstart;
    
    import com.mongodb.client.MongoClient;
    import com.mongodb.client.MongoClients;
    import org.bson.Document;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Connection {
    
        public static void main(String[] args) {
            String connectionString = System.getProperty("mongodb.uri");
            try (MongoClient mongoClient = MongoClients.create(connectionString)) {
                List<Document> databases = mongoClient.listDatabases().into(new ArrayList<>());
                databases.forEach(db -> System.out.println(db.toJson()));
            }
        }
    }

    2. In the project's root folder, run the following command to compile your Maven project and connect to your Atlas cluster: 

    mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection" -Dmongodb.uri="<connectionString>"mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection" -Dmongodb.uri="<connectionString>"