Hackforge Academy

Category: React • Beginner

Published on 05 Mar 2026

Explanation

First, add the MongoDB Java Driver dependency to your project (Maven example shown). This allows Java to communicate with MongoDB.

Code Example

Add Maven Dependency:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>
    mongodb-driver-sync
   </artifactId>
  <version>4.11.1</version>
</dependency>

Explanation

Import the required MongoDB client classes.

Code Example

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

Explanation

Create a MongoClient instance to connect to the MongoDB server running on localhost at port 27017.

Code Example

MongoClient mongoClient = 
MongoClients.create("mongodb://hostname");

Explanation

Connect to a specific database. If the database does not exist, MongoDB will create it automatically when data is inserted.

Code Example

MongoDatabase database = mongoClient.
getDatabase("testdb");
//message after sucess
System.out.println("Connected successfully!");

//closing connection
mongoClient.close();

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.