In this blog post we will learn how to connect or use MongoDB using Java programming language.

The first step is to get a MonogDB server up and running, for installation process you can follow the MongoDB Installation process.

If you don't want to get into the hassel of setting up server and installation, sign up for MongoDB Free Tier

Connecting to the Shell

Connecting to mongodb shell is easy if you have monogdb-client installed, if not you can download by clicking this link. Extract the folder to find mongo client inside ./bin folder.
If you signed-up for MongoDB Cloud server, follow below steps to find your connection string.

  1. Login into your cloud account

  2. Click Cluster menu on the left side of the page , then click Connect button, as seen in the image below.


  1. Find your connections string as seen in the below picture, copy and paste the connection string in the terminal, don't forget to change the username, you will be prompted for password after hitting the enter key.


Setting up your IDE for development

I will be using visualstudio code, with Java Extension installed, you can use your favourite one.

Generally IDE like Eclipse automates lots of things under the hood, but we will be using terminal to perform most of the operation, which is good to learn core things.

Install Maven
We will use Maven build system to create our project, to do so follow the below steps.
If you already have Maven installed, skip to the Creating Project section.

Below steps were carried out on Ubuntu, but you can simulate same on other platforms as well.

  1. Download Maven
  2. Move mv ~/Downloads/apache-maven-3.5.3-bin.tar.gz /opt/
  3. Extract tar xzvf apache-maven-3.5.3-bin.tar.gz
  4. Add maven to path export PATH=/opt/apache-maven-3.5.3/bin:$PATH
  5. Verify if maven is setup correctly by running command mvn -v, one should see below output.
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-25T01:19:05+05:30)
Maven home: /opt/apache-maven-3.5.3
Java version: 1.8.0_152, vendor: Oracle Corporation
Java home: /opt/jdk/jdk1.8.0_152/jre
Default locale: en_IN, platform encoding: UTF-8
OS name: "linux", version: "4.13.0-43-generic", arch: "amd64", family: "unix"

Creating Project
Run the command mvn archetype:generate -DartifactId=todo-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false on the terminal.

At this point you should have below directory structure.

├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── techexpander
│   │               └── app
│   │                   └──
│   └── test
│       └── java
│           └── com
│               └── techexpander
│                   └── app
│                       └──

  1. To load the project in visualstudio code IDE, run code . from within the todo-app directory.

Connecting to your application

Connecting to MongoDB server using Java requires installation of mongodb-java-driver, so lets install that first.

Install mongodb-java-driver
Edit pom.xml file to look like below.

<project xmlns="" xmlns:xsi=""

Connecting MongoDB Server
Edit todo-app/src/main/java/com/techexpander/app/ to include below changes.

// Import statements
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

public class App
    public static void main( String[] args )
        // Connect to MongoDB atlas server
        MongoClient mongoClient = MongoClients.create("mongodb+srv://" + URLEncoder.encode("{username}") + ":" + URLEncoder.encode("{password}") + "@{clusterConnectionString}/");
        // Get ToDo database
        MongoDatabase database = mongoClient.getDatabase("ToDo");

        // Get tasks collection
        MongoCollection<Document> coll = database.getCollection("tasks");

        // Drop all documents from collection.

Replace {username}, {password} and {clusterConnectionString} with yours one.

Basic CRUD operations: Creating a document, saving it to the database and querying for that same document again

Insert single task

// Prepare task document to be inserted
Document doc = new Document("text", "Learn MongoDB")
    .append("owner", "Dipak")
    .append("priority", "high")
    .append("checked", true);
// Insert one task document

Insert multiple task
import java.util.ArrayList;

// ArrayList to store list of task docuemnts
ArrayList<Document> docs = new ArrayList<Document>();

// Add task Document to docs array
	new Document("text", "Learn Java")
		.append("owner", "Dipak")
		.append("priority", "medium")
		.append("checked", true)

// Add another task Document to docs array
	new Document("text", "Release MongoDB 4.0")
		.append("owner", "MongoDB Inc.")
		.append("priority", "high")
		.append("checked", true)

// Insert multiple task documents

Retrive/Fetch tasks
import static com.mongodb.client.model.Filters.eq;

// Find first task document
Document firstDoc = coll.find().first();

// find all task documents.
for (Document cur : coll.find()) {

// find all task documents with high priority.
coll.find(eq("priority", "high"));
for (Document cur : coll.find()) {

Update tasks
import static com.mongodb.client.model.Updates.set;

// Update priority to high for "Learn Java" task
coll.updateOne(eq("text", "Learn Java"), set("priority", "high"));

// Uncheck all task assigned to Dipak
UpdateResult updateResult = coll.updateMany(eq("owner", "Dipak"), set("checked", false));

Deleting all tasks and droping database
import com.mongodb.client.result.DeleteResult;

// Delete task assigned to MongoDB Inc.
coll.deleteOne(eq("owner", "MongoDB Inc."));

// Delete Many
DeleteResult deleteResult = coll.deleteMany(eq("owner", "Dipak"));

// drop task collection.

// drop database
// Note: use should have permission to dropDatabase

// Close monogdb connection

Building the project and running
Edit pom.xml file, and paste the below code inside the <project> tag.

				<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">

Open the terminal and cd into the project directory and run mvn clean install && mvn package.
That should package the project into executable jar file and place it in the target directory target/todo-app-1.0-SNAPSHOT.jar
To run the jar file run the command java -jar target/todo-app-1.0-SNAPSHOT.jar and you should see the output we printed from the Main file.

Source Code for this project can be found on github, don't forget to star the repo.

Hope you enjoyed reading this article, feel free to share so others can learn!!.