Introduction

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 https://cloud.mongodb.com/

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

Selection_013

  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.

Selection_012

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 -DgroupId=com.techexpander.app -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
│   │                   └── App.java
│   └── test
│       └── java
│           └── com
│               └── techexpander
│                   └── app
│                       └── AppTest.java

  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="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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.techexpander.app</groupId>
  <artifactId>todo-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>todo-app</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>3.7.1</version>
    </dependency>
  </dependencies>
</project>

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

// Import statements
import java.net.URLEncoder;
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.
        coll.drop();
}

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
coll.insertOne(doc);

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
docs.add(
	new Document("text", "Learn Java")
		.append("owner", "Dipak")
		.append("priority", "medium")
		.append("checked", true)
);

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

// Insert multiple task documents
coll.insertMany(docs);

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

// Find first task document
Document firstDoc = coll.find().first();
System.out.println(firstDoc.toJson());


// find all task documents.
for (Document cur : coll.find()) {
	System.out.println(cur.toJson());
}

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

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));
System.out.println(updateResult.getModifiedCount());

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"));
System.out.println(deleteResult.getDeletedCount());

// drop task collection.
coll.drop();

// drop database
// Note: use should have permission to dropDatabase
database.drop();

// Close monogdb connection
mongoClient.close();

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

<build>
	<plugins>
		<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-shade-plugin</artifactId>
		<version>2.3</version>
		<executions>
			<execution>
			<phase>package</phase>
			<goals>
				<goal>shade</goal>
			</goals>
			<configuration>
				<transformers>
				<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
					<mainClass>com.techexpander.app.App</mainClass>
				</transformer>
				</transformers>
			</configuration>
			</execution>
		</executions>
		</plugin>
	</plugins>
</build>

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