Connect to MongoDB from Java using MongoDB Java Driver
Connect to MongoDB from Java – In this MongoDB Tutorial, we shall learn to connect to MongoDB from Java Application.
A Java application connects to MongoDB through the official MongoDB Java driver. The driver creates a MongoClient, uses a MongoDB connection string or host and port details, and then lets your code access databases and collections.
This tutorial keeps the original legacy driver example and also shows the current recommended style with the synchronous MongoDB Java driver. Use the modern mongodb-driver-sync dependency for new Java projects. Use the older mongo-java-driver style only when maintaining old applications that already use the 3.x driver API.
Prerequisites to connect Java application to MongoDB
- Java JDK installed and configured.
- A running MongoDB server on your local machine or a MongoDB Atlas cluster.
- A Java project created in IntelliJ IDEA, Eclipse, Maven, Gradle, or any build tool of your choice.
- MongoDB Java driver dependency added to the project.
- Network access to the MongoDB host and the correct username and password if authentication is enabled.
For a local MongoDB installation, the default host is usually localhost or 127.0.0.1, and the default port is 27017. For MongoDB Atlas, copy the connection string from the Atlas cluster connection screen and replace the username, password, and database values as required.
1. Download MongoDB Java Driver
Download latest available MongoDB Java Driver from Maven Repository.
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/
For this tutorial, we shall download 3.5.0, which was then latest.
For new Java applications, prefer adding the official synchronous driver as a Maven or Gradle dependency instead of manually downloading a JAR. The modern artifact is org.mongodb:mongodb-driver-sync. The older mongo-java-driver artifact is useful when you are following legacy examples that import com.mongodb.MongoClient.
Maven dependency for current MongoDB Java sync driver
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.2.1</version>
</dependency>
Gradle Kotlin DSL dependency for current MongoDB Java sync driver
dependencies {
implementation("org.mongodb:mongodb-driver-sync:5.2.1")
}
You may change the version to the latest stable version available in Maven Central or the official MongoDB Java driver documentation.
2. Add MongoDB driver JAR or dependency to Java build path
In IntelliJ IDEA, copy the jar file to lib folder, then right click on the jar file and ‘Add as Library’.
In Eclipse, follow this menu navigation path: Project -> Properties -> Java Build Path -> Libraries -> Add Jars -> Select the jar -> Click “Apply” -> Click “OK”.
If you use Maven or Gradle, you do not need to manually add the JAR to the build path. Add the dependency in pom.xml or build.gradle, refresh the project, and let the build tool download the required driver libraries.
3. Create MongoClient
In your Java Program, create a new MongoClient with host and port provided as arguments to the constructor.
MongoClient mongoClient = new MongoClient( host , port );
host (String) and port (Integer) are IP Address or hostname and Port Number respectively at which MongoDB Daemon Service is running.
With the details provided, mongoClient creates a new Client to the MongoDB.
In the current synchronous driver, create the client using MongoClients.create(). This method accepts a connection string and returns a com.mongodb.client.MongoClient instance.
MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
For MongoDB Atlas, the connection string usually uses the mongodb+srv format.
String connectionString = "mongodb+srv://<username>:<password>@<cluster-url>/?retryWrites=true&w=majority";
MongoClient mongoClient = MongoClients.create(connectionString);
Do not hard-code production usernames and passwords directly in source code. Read them from environment variables, a secrets manager, or your application configuration system.
4. MongoClient is Ready
If there is no exception thrown during MongoClient creation, your MongoClient is successfully connected to MongoDB.
In many driver versions, the client object can be created before a real server command is sent. To verify the MongoDB connection from Java, run a small command such as ping after creating the client.
mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
System.out.println("Connected to MongoDB!");
This is useful because it confirms that the Java application can reach the MongoDB server and that the connection string is valid.
5. Close connection to MongoDB
Once you are done with the MongoDB Operations, close the connection between MongoClient and MongoDB Daemon Service.
mongoClient.close();
In modern Java code, prefer a try-with-resources block. It closes the MongoClient automatically when the block finishes.
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
System.out.println("Connected to MongoDB!");
}
Example – Connection to MongoDB using Java
Following is an example Java Program to demonstrate on how to establish a connection to MongoDB by creating a MongoClient :
example.java
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
/**
* Created by TutorialKart on 31/10/17.
*/
public class JavaMongoConnectionExample {
public static void main(String[] args) {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "127.0.0.1" , 27017 );
System.out.println("Connected to MongoDB!");
} catch (MongoException e) {
e.printStackTrace();
} finally {
if(mongoClient!=null)
mongoClient.close();
}
}
}
Console Output
Nov 01, 2017 8:52:44 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connected to MongoDB!
Modern Java example to connect MongoDB and run ping command
The following example uses the current synchronous MongoDB Java driver API. It creates a client, sends a ping command to the admin database, and prints a success message.
JavaMongoConnectionCurrentDriverExample.java
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.bson.Document;
public class JavaMongoConnectionCurrentDriverExample {
public static void main(String[] args) {
String connectionString = "mongodb://localhost:27017";
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
System.out.println("Connected to MongoDB!");
} catch (Exception e) {
System.err.println("Could not connect to MongoDB: " + e.getMessage());
}
}
}
Output
Connected to MongoDB!
Connect Java to MongoDB Atlas using connection string
To connect a Java application to MongoDB Atlas, copy the SRV connection string from your Atlas cluster. Replace the placeholders with your database user, password, and cluster address.
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.bson.Document;
public class JavaMongoAtlasConnectionExample {
public static void main(String[] args) {
String username = System.getenv("MONGODB_USERNAME");
String password = System.getenv("MONGODB_PASSWORD");
String cluster = System.getenv("MONGODB_CLUSTER");
String connectionString = "mongodb+srv://" + username + ":" + password + "@" + cluster + "/?retryWrites=true&w=majority";
try (MongoClient mongoClient = MongoClients.create(connectionString)) {
mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
System.out.println("Connected to MongoDB Atlas!");
}
}
}
If the password contains special characters, encode it properly for use in a URI. Also make sure your Atlas network access list allows your application server IP address.
Create or access MongoDB database and collection from Java
After the connection is ready, get a database and collection using the Java driver. MongoDB creates the database or collection when you first write data to it.
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class JavaMongoInsertExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("school");
MongoCollection<Document> students = database.getCollection("students");
Document student = new Document("name", "Arun")
.append("class", "10")
.append("subject", "Mathematics");
students.insertOne(student);
System.out.println("Document inserted successfully.");
}
}
}
Output
Document inserted successfully.
Common MongoDB Java connection errors and fixes
| Error or symptom | Likely reason | What to check |
|---|---|---|
Connection refused | MongoDB is not running or the port is wrong. | Start MongoDB and check host and port. Local default port is 27017. |
Authentication failed | Invalid username, password, auth database, or user permissions. | Verify credentials and the database against which the user is authenticated. |
| Atlas connection times out | IP address is not allowed or network is blocked. | Check Atlas Network Access and firewall rules. |
ClassNotFoundException | MongoDB driver is missing from classpath. | Add the Maven or Gradle dependency and refresh the project. |
| Program creates client but fails later | The client was created, but no server command was run yet. | Run ping to verify the connection immediately. |
MongoDB Java driver imports: legacy API and current API
The import statements are different for older and newer MongoDB Java driver examples. If you copy code from different tutorials, check the package names carefully.
| Driver style | Typical dependency | MongoClient import | Client creation |
|---|---|---|---|
| Legacy 3.x style | mongo-java-driver | com.mongodb.MongoClient | new MongoClient("127.0.0.1", 27017) |
| Current sync driver style | mongodb-driver-sync | com.mongodb.client.MongoClient | MongoClients.create(connectionString) |
For new code, the current sync driver style is usually the better choice. For old applications, update only after checking compatibility with the existing codebase.
Security notes for MongoDB connection strings in Java
- Do not commit MongoDB usernames and passwords to Git repositories.
- Use environment variables or secure configuration files for credentials.
- Use a database user with only the permissions required by the application.
- Use TLS-enabled connection strings for production deployments where required.
- For MongoDB Atlas, keep the IP access list as narrow as practical.
QA checklist for this Java MongoDB connection tutorial
- Confirm that the tutorial distinguishes old
mongo-java-driverexamples from the currentmongodb-driver-syncAPI. - Verify that every new Java code sample imports
com.mongodb.client.MongoClientandcom.mongodb.client.MongoClientswhere the current driver is used. - Check that connection strings do not contain real usernames, passwords, or cluster names.
- Confirm that MongoDB Atlas instructions mention replacing placeholders and allowing the application IP address.
- Run the local example only after MongoDB is running on
localhost:27017.
FAQs on connecting MongoDB from Java application
How do I connect a Java application to MongoDB?
Add the MongoDB Java driver dependency, create a MongoClient with a connection string, and run a command such as ping to verify the connection. For new projects, use MongoClients.create("mongodb://localhost:27017") with the synchronous driver.
Which MongoDB Java driver dependency should I use?
For new synchronous Java applications, use org.mongodb:mongodb-driver-sync. Older examples may use org.mongodb:mongo-java-driver, but that belongs to the legacy API style.
How do I check whether Java is really connected to MongoDB?
Run a simple command after creating the client, such as mongoClient.getDatabase("admin").runCommand(new Document("ping", 1)). If the command succeeds, the application can reach the MongoDB server.
What is the default MongoDB URL for a local Java application?
The usual local MongoDB connection string is mongodb://localhost:27017. You can also use mongodb://127.0.0.1:27017 when MongoDB is running on the same machine.
Can I connect Java to MongoDB Atlas?
Yes. Copy the mongodb+srv connection string from MongoDB Atlas, replace the placeholders, add your application IP address to the Atlas access list, and create the Java client using MongoClients.create(connectionString).
References
Conclusion
In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Java Application using MongoDB Java Driver.
For new Java applications, add the current MongoDB synchronous driver, create the client with MongoClients.create(), verify the connection with a ping command, and close the client after use. For older applications, the legacy new MongoClient(host, port) style can still explain existing code, but new development should follow the current driver API.
TutorialKart.com