MongoDB - Java
Modern MongoDB with Java
Section titled “Modern MongoDB with Java”This tutorial guides you through setting up a modern Java project to interact with a MongoDB database using the official MongoDB Java Driver.
Project Setup with a Build Tool
Section titled “Project Setup with a Build Tool”Modern Java development relies on build tools like Maven or Gradle to manage dependencies. Manually downloading JAR files is an outdated and error-prone practice. You only need to add the MongoDB Java Driver dependency to your project’s configuration file.
Maven Dependency (pom.xml)
Section titled “Maven Dependency (pom.xml)”<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> <!-- Use the latest stable version --> </dependency> <!-- For logging, which is highly recommended --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>2.0.7</version> </dependency></dependencies>Gradle Dependency (build.gradle.kts)
Section titled “Gradle Dependency (build.gradle.kts)”dependencies { // Use the latest stable version implementation("org.mongodb:mongodb-driver-sync:4.11.1")
// For logging, which is highly recommended implementation("org.slf4j:slf4j-simple:2.0.7")}Connecting to MongoDB
Section titled “Connecting to MongoDB”The modern and recommended way to connect is by using a connection string with MongoClients.create(). This single string can contain the host, port, authentication credentials, and other connection options. It’s secure and flexible.
The try-with-resources statement ensures that the MongoClient instance is automatically closed when the block is exited, which properly releases all database resources.
import com.mongodb.client.*;import org.bson.Document;
import static com.mongodb.client.model.Filters.eq;import static com.mongodb.client.model.Updates.set;
public class MongoCrudExample {
public static void main(String[] args) { // Replace with your MongoDB Atlas connection string or local instance URI String uri = "mongodb://localhost:27017"; // Example for a local instance // For Atlas: "mongodb+srv://<username>:<password>@cluster.mongodb.net/?retryWrites=true&w=majority"
try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("myModernDb"); MongoCollection<Document> collection = database.getCollection("users");
System.out.println("Successfully connected to database: " + database.getName());
// 1. Clean up previous data collection.drop(); System.out.println("\n--- Dropped existing collection ---");
// 2. Create / Insert a Document Document newUser = new Document("name", "Ada Lovelace") .append("email", "ada@example.com") .append("country", "UK") .append("projects", 10); collection.insertOne(newUser); System.out.println("\n--- Inserted a document ---"); System.out.println(newUser.toJson());
// 3. Read / Find a Document System.out.println("\n--- Reading the document ---"); Document foundUser = collection.find(eq("name", "Ada Lovelace")).first(); if (foundUser != null) { System.out.println("Found user: " + foundUser.toJson()); } else { System.out.println("User not found."); }
// 4. Update a Document collection.updateOne(eq("name", "Ada Lovelace"), set("projects", 12)); System.out.println("\n--- Updated the document ---"); Document updatedUser = collection.find(eq("name", "Ada Lovelace")).first(); System.out.println("User after update: " + updatedUser.toJson());
// 5. Delete a Document collection.deleteOne(eq("name", "Ada Lovelace")); System.out.println("\n--- Deleted the document ---"); long count = collection.countDocuments(); System.out.println("Documents in collection: " + count);
} catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } }}Expected Output
Section titled “Expected Output”Successfully connected to database: myModernDb
--- Dropped existing collection ---
--- Inserted a document ---{ "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 10 }
--- Reading the document ---Found user: { "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 10 }
--- Updated the document ---User after update: { "_id": { "$oid": "..." }, "name": "Ada Lovelace", "email": "ada@example.com", "country": "UK", "projects": 12 }
--- Deleted the document ---Documents in collection: 0Key Modernization Points
Section titled “Key Modernization Points”- Dependency Management: Use Maven or Gradle instead of manual JARs.
- Connection: Use
MongoClients.create(uri)with a connection string for simplicity and security. - Resource Management: Use
try-with-resourcesto ensure theMongoClientis always closed correctly. - CRUD Operations: Use modern, explicit methods like
insertOne,updateOne,deleteOne,find, andcountDocuments. - Error Handling: Wrap database logic in a
try-catchblock to handle potential exceptions gracefully.