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();