Quick Start: Java and MongoDB - Starting and Setup

Maxime Beugnet

Quick Start Java and MongoDB

In this very first blog post of the Java Quick Start series, I will show you how to set up your Java project with Maven and execute a MongoDB command in Java.

In the future parts, we will move on and work through:

  • Database Create, Read, Update and Delete (CRUD) operations
  • Mapping MongoDB BSON documents directly to Plain Old Java Object (POJO)
  • The MongoDB Aggregation Framework
  • Change Streams
  • Multi-document ACID transactions
  • The MongoDB Java reactive streams driver.

Why Java and MongoDB? Java is the most popular language in the IT industry at the date of this blog post, and developers voted MongoDB as their most wanted database four years in a row. In this series of blog posts, I will be demonstrating how powerful these two great pieces of technology are when combined and how you can access that power.

To follow along, you can use any environment you like and the integrated development environment of your choice. I’ll use Maven 3.6.2 and the Java OpenJDK 13, but all the code will be compatible with Java versions 8 to 13 so feel free to use the JDK of your choice and update the Java version accordingly in the pom.xml file we are about to setup.

For the MongoDB Cluster, we will be using a M0 Free Tier MongoDB Cluster from MongoDB Atlas. If you don't have one already, check out my Get started with an M0 cluster blog post.

Get your free M0 cluster on MongoDB Atlas today. It's free forever, and you'll be able to use it to work with the examples in this blog series.

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:

├── 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"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">






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] --------------------< com.mongodb:java-quick-start >--------------------
[INFO] Building java-quick-start 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[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] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ java-quick-start ---
[INFO] Nothing to compile - all classes are up to date
[INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ java-quick-start ---
Hello MongoDB!
[INFO] ------------------------------------------------------------------------
[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) {
        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}

Java and MongoDB

If you want to learn more and deepen your knowledge faster, I recommend you check out the M220J: MongoDB for Java Developers training available for free on MongoDB University.

Sky’s the limit with Java and MongoDB, so please join me in this Quick Start series to get more tips and tricks about how to combine these two awesome technologies together.

Articles in this Quick Start Java and MongoDB series: