Signup/Sign In

Java Integration with MongoDB

In this, we will learn how to integrate MongoDB with Java and will explore the basic CRUD (Create, Retrieve, Update and Delete) operations.

Download Jar, use mongo-java-driver-3.10.0.jar. Add jar to the Java build path. Now, we are ready for performing CRUD operations with MongoDB through Java.

Here, we are making use of MongoDB Compass - a GUI tool for MongoDB for visualizing our query output.

We can connect to the DB using this user interface and then test our queries here.

Java Integration in MongoDB


Java Code to Make Connection with MongoDB

First we must add the mongo-java-driver-3.10.0.jar file as a dependency in our Java project. So we will be adding Maven dependency like this:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.10.0</version>
</dependency>

To find the latest version of the above Mongo Java driver, check the following link.

Below we have a simple Java class with a main() method which uses the MongoClient class to setup connection with MongoDB.

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient; 

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			System.out.println("Database DemoDB connected successfully");
		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

When the above mentioned code is executed, following output will be produced on console:

Java Integration in MongoDB


NOTE: If you are using an older version of the mongodb java driver which is <= 2.10.0, then you should use the following code with Mongo class to create the connection.

// code to create the connection
Mongo mongo = new Mongo("localhost", 27017); 
// code to connect to the database
DB db = mongoClient.getDB("DemoDB");

If your MongoDB is running in authenticated mode, then you will have to provide the username and password while connecting to the database, like this:

// code to connect to the database with authentication
DB db = mongoClient.getDB("DemoDB");
boolean auth = db.authenticate("username", "password".toCharArray());

MongoDB: Show all Databases

Once we are able to successfully establish connection using MongoClient, we can use the following code to display all the databases available:

// display all the databases
mongoClient.getDatabaseNames().forEach(System.out::println);

The output for the above code will be:

local 0.000GB DemoDB 0.000GB

The above java code which is used to display list of all the databases is similar to the MySQL command show databases;


MongoDB: Create a Collection

If we want to create a collection(just like table in relational DB) from our java program, we can do so like this:

package com.mongo;

import com.mongodb.DB; 
import com.mongodb.MongoClient;
import com.mongodb.BasicDBObject; 

public class MakeConnection { 
	public static void main(String[] args) {
		try { 
			// code to create the connection
			MongoClient mongoClient = new MongoClient("localhost", 27017); 
			// code to connect to the database
			DB db = mongoClient.getDB("DemoDB");

			db.createCollection("User", new BasicDBObject());
			System.out.println("Collection User created successfully");

		} 
		catch(Exception e) { 
			e.printStackTrace(); 
		} 
	}
}

Upon executing the above code, a new collection with name User will get created in our database.

You can see the collections in the MongoDB Compass UI as well.

Java Integration in MongoDB