Let’s jump in and take a look at how well Java and MongoDB work together.

Getting Set Up

To begin with, we will need to setup a new Maven project. You have two options at this point. You can either clone this series’ git repository or you can create and set up the maven project.

Using the Git repository

If you choose to use git, you will get all the code immediately. I still recommend you read through the manual set up.

You can clone the repository if you like with the following command.

git clone https://github.com/mongodb-developer/java-quick-start

Or you can download the repository as a zip file using this link.

Setting Up Manually

You can either use your favorite IDE to create a new Maven project for you or you can create the Maven project manually. Either way, you should get the following folder architecture:

java-quick-start/
├── pom.xml
└── src
    └── main
        └── java
            └── com
                └── mongodb
                    └── quickstart

The pom.xml file should contain the following code:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mongodb</groupId>
    <artifactId>java-quick-start</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven-compiler-plugin.source>8</maven-compiler-plugin.source>
        <maven-compiler-plugin.target>8</maven-compiler-plugin.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mongodb-driver-sync.version>3.11.0</mongodb-driver-sync.version>
        <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>${mongodb-driver-sync.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compiler-plugin.version}</version>
                <configuration>
                    <source>${maven-compiler-plugin.source}</source>
                    <target>${maven-compiler-plugin.target}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

To verify that everything works correctly, you should be able to create and run a simple “Hello MongoDB!” program. In src/main/java/com/mongodb/quickstart, create the HelloMongoDB.java file:

package com.mongodb.quickstart;

public class HelloMongoDB {

    public static void main(String[] args) {
        System.out.println("Hello MongoDB!");
    }
}

Then compile and execute it with your IDE or use the command line in the root directory (where the src folder is):

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.HelloMongoDB"

The result should look like this:

[...]
[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-quick-start ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ java-quick-start ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ java-quick-start ---
Hello MongoDB!
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.786 s
[INFO] Finished at: 2019-10-02T20:19:36+02:00
[INFO] ------------------------------------------------------------------------

Note: If you see some warnings about an illegal reflective access from guice.java, it’s safe to ignore them. Guice is used by Maven and needs an update. You can read more about it here. These warnings will disappear in a future release of Guice and Maven.

Putting the Driver to Work

Now that our Maven project works, we can start talking with MongoDB.

If you have imported the Sample Dataset as suggested in the Quick Start Atlas blog post, then with the Java code we are about to create, you will be able to see a list of the databases in the sample Dataset.

The first step is to instantiate a MongoClient by passing a MongoDB Atlas connection string into the MongoClients.create() static method. This will establish a connection to MongoDB Atlas using the connection string. Then we can retrieve the list of databases on this cluster and print them out to test the connection with MongoDB.

In src/main/java/com/mongodb, create the Connection.java file:

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;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Connection {

    public static void main(String[] args) {
        Logger.getLogger("org.mongodb.driver").setLevel(Level.WARNING);
        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()));
        }
    }
}

As you can see, the MongoDB connection string is retrieved from the System Properties so we need to set this up. Once you have retrieved your MongoDB Atlas connection string, you can add the mongodb.uri system property into your IDE. Here is my configuration with IntelliJ for example.

IntelliJ Configuration

Or if you prefer to use Maven in command line, here is the equivalent command line you can run in the root directory:

mvn compile exec:java -Dexec.mainClass="com.mongodb.quickstart.Connection" -Dmongodb.uri="mongodb+srv://username:password@cluster0-abcde.mongodb.net/test?w=majority"

Note: Don’t forget the double quotes around the MongoDB URI to avoid surprises from your shell.

The standard output should look like this:

{"name": "admin", "sizeOnDisk": 303104.0, "empty": false}
{"name": "config", "sizeOnDisk": 147456.0, "empty": false}
{"name": "local", "sizeOnDisk": 5.44731136E8, "empty": false}
{"name": "sample_airbnb", "sizeOnDisk": 5.761024E7, "empty": false}
{"name": "sample_geospatial", "sizeOnDisk": 1384448.0, "empty": false}
{"name": "sample_mflix", "sizeOnDisk": 4.583424E7, "empty": false}
{"name": "sample_supplies", "sizeOnDisk": 1339392.0, "empty": false}
{"name": "sample_training", "sizeOnDisk": 7.4801152E7, "empty": false}
{"name": "sample_weatherdata", "sizeOnDisk": 5103616.0, "empty": false}

#mongodb #java #web-development

Developing Apps with MongoDB and Java
2.70 GEEK