MongoDB Java Driver
Enterprise-grade MongoDB integration for Java applications
☕ What is MongoDB Java Driver?
The MongoDB Java Driver provides a robust, type-safe way to interact with MongoDB from Java applications. It offers both synchronous and asynchronous APIs, making it perfect for enterprise applications requiring high performance and reliability.
// Simple Java connection
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
MongoClient client = MongoClients.create("mongodb://localhost:27017");
System.out.println("Connected to MongoDB!");
Key Features
Type Safety
Strong typing with Java generics
Performance
Optimized for enterprise workloads
Builder Pattern
Fluent API for queries and updates
Enterprise Ready
Production-grade features
🔹 Maven Dependency
Add the MongoDB Java Driver to your project using Maven or Gradle. This dependency includes all necessary libraries for connecting to MongoDB and performing database operations with full Java integration.
<!-- Add to pom.xml -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.0</version>
</dependency>
// Gradle
implementation 'org.mongodb:mongodb-driver-sync:4.11.0'
🔹 Connecting to MongoDB
Establish a connection using MongoClients factory class. The driver manages connection pooling automatically, ensuring efficient resource usage. Access databases and collections through a clean, type-safe API.
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
public class MongoDBConnection {
public static void main(String[] args) {
// Create connection
MongoClient client = MongoClients.create("mongodb://localhost:27017");
// Access database
MongoDatabase database = client.getDatabase("myDatabase");
// Access collection
MongoCollection<Document> collection = database.getCollection("users");
System.out.println("Connected successfully!");
// Close connection
client.close();
}
}
🔹 Insert Documents
Insert documents using the Document class, which represents BSON documents. You can insert single documents with insertOne() or multiple documents efficiently with insertMany(), receiving confirmation of successful insertions.
import org.bson.Document;
import java.util.Arrays;
// Insert one document
Document user = new Document("name", "John Doe")
.append("email", "[email protected]")
.append("age", 30)
.append("hobbies", Arrays.asList("reading", "coding"));
collection.insertOne(user);
System.out.println("Inserted ID: " + user.getObjectId("_id"));
// Insert multiple documents
Document user1 = new Document("name", "Alice")
.append("email", "[email protected]")
.append("age", 25);
Document user2 = new Document("name", "Bob")
.append("email", "[email protected]")
.append("age", 35);
collection.insertMany(Arrays.asList(user1, user2));
System.out.println("Inserted multiple documents");
Output:
Inserted ID: 507f1f77bcf86cd799439011
Inserted multiple documents
🔹 Find Documents
Query documents using the Filters builder class for type-safe query construction. Retrieve documents as an iterable collection, allowing you to process results efficiently with Java streams or traditional loops.
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import static com.mongodb.client.model.Filters.*;
// Find all documents
FindIterable<Document> allUsers = collection.find();
for (Document doc : allUsers) {
System.out.println(doc.toJson());
}
// Find with filter
FindIterable<Document> adults = collection.find(gte("age", 18));
for (Document doc : adults) {
System.out.println(doc.getString("name"));
}
// Find one document
Document user = collection.find(eq("name", "John Doe")).first();
System.out.println("Found: " + user.getString("name"));
// Find with projection
FindIterable<Document> names = collection.find()
.projection(new Document("name", 1).append("email", 1).append("_id", 0));
for (Document doc : names) {
System.out.println(doc.toJson());
}
Output:
{"name": "John Doe", "email": "[email protected]", "age": 30}
Found: John Doe
🔹 Update Documents
Modify documents using the Updates builder class for type-safe update operations. The driver supports various update operators including set, increment, push, and more for flexible document modifications.
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
// Update one document
UpdateResult result = collection.updateOne(
eq("name", "John Doe"),
combine(set("age", 31), set("city", "New York"))
);
System.out.println("Modified: " + result.getModifiedCount());
// Update many documents
UpdateResult multiResult = collection.updateMany(
lt("age", 30),
set("status", "young")
);
System.out.println("Updated: " + multiResult.getModifiedCount());
// Increment a value
collection.updateOne(
eq("name", "John Doe"),
inc("age", 1)
);
// Add to array
collection.updateOne(
eq("name", "John Doe"),
push("hobbies", "gaming")
);
Output:
Modified: 1
Updated: 2
🔹 Delete Documents
Remove documents from collections using deleteOne() for single documents or deleteMany() for bulk deletions. The driver returns detailed results including the count of deleted documents for verification.
import com.mongodb.client.result.DeleteResult;
import static com.mongodb.client.model.Filters.*;
// Delete one document
DeleteResult result = collection.deleteOne(eq("name", "John Doe"));
System.out.println("Deleted: " + result.getDeletedCount());
// Delete many documents
DeleteResult multiResult = collection.deleteMany(lt("age", 18));
System.out.println("Deleted: " + multiResult.getDeletedCount());
// Delete all documents
DeleteResult allResult = collection.deleteMany(new Document());
System.out.println("All deleted: " + allResult.getDeletedCount());
Output:
Deleted: 1
Deleted: 3
🔹 Aggregation Pipeline
Build complex data processing pipelines using the Aggregates builder class. Combine multiple stages like match, group, sort, and project to perform sophisticated data analysis and transformations directly in the database.
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Accumulators;
import java.util.Arrays;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Aggregates.*;
// Aggregation pipeline
List<Document> results = collection.aggregate(Arrays.asList(
match(gte("age", 18)),
group("$city",
Accumulators.avg("avgAge", "$age"),
Accumulators.sum("count", 1)
),
sort(new Document("avgAge", -1))
)).into(new ArrayList<>());
for (Document doc : results) {
System.out.println(doc.toJson());
}
Output:
{"_id": "New York", "avgAge": 32.0, "count": 5}
🔹 POJO Support
Map MongoDB documents directly to Java objects using POJO (Plain Old Java Object) support. This provides type safety and eliminates manual document parsing, making your code cleaner and more maintainable.
import org.bson.codecs.pojo.annotations.BsonProperty;
import org.bson.types.ObjectId;
// Define POJO class
public class User {
private ObjectId id;
private String name;
private String email;
private int age;
// Constructors, getters, setters
public User() {}
public User(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
// Getters and setters...
}
// Use POJO with collection
MongoCollection<User> userCollection = database
.getCollection("users", User.class);
// Insert POJO
User user = new User("John Doe", "[email protected]", 30);
userCollection.insertOne(user);
// Find POJO
User foundUser = userCollection.find(eq("name", "John Doe")).first();
System.out.println(foundUser.getEmail());
🔹 Error Handling
Implement comprehensive error handling using MongoDB's exception hierarchy. Catch specific exceptions for different error scenarios like connection failures, duplicate keys, or timeout issues to build resilient applications.
import com.mongodb.MongoException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.DuplicateKeyException;
try {
MongoClient client = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = client.getDatabase("myDB");
MongoCollection<Document> collection = database.getCollection("users");
Document user = new Document("email", "[email protected]")
.append("name", "Test User");
collection.insertOne(user);
System.out.println("Operation successful");
} catch (DuplicateKeyException e) {
System.err.println("Duplicate key error: " + e.getMessage());
} catch (MongoTimeoutException e) {
System.err.println("Connection timeout: " + e.getMessage());
} catch (MongoException e) {
System.err.println("MongoDB error: " + e.getMessage());
} finally {
if (client != null) {
client.close();
}
}