Hackforge Academy

Category: java

java with mongodb

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:

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:

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:

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:

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

//closing connection
mongoClient.close();

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community