Developing Apps with MongoDB and Java

Developing Apps with MongoDB and Java

Want to get started with MongoDB and Java? Developing Apps with MongoDB and Java - Learn how to set up your Java project with Maven and execute a MongoDB command in Java.

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

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=""






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 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, 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 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.

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:[email protected]/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}

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now:

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

Web Development Services

Web Development Services

As one of the best Web Application Development Company, it provides a fine quality mobile app development service at an affordable price. Especially, it encourage start-ups that have unique ideas, by offering a more competitive price

HireFullStackDeveloperIndia is rated as one of the top Web Application Development Company in India by various industry magazines and review sites. They have a right blend of award-winning designers, expert programmers and Google certified digital marketers which make them a unique one-stop solution for hundreds of our clients, spread across all countries.

A Good website reflects not only your business but also it is one of the main factors why a potential customer would convert into Client. A good website design helps increase traffic driving leads to grow business. The best web design company create a custom design for each corporate website so as to help them meet their business goals.

Get Quote: