In this section, we will explore how to integrate MongoDB with Java. We will cover the following topics:
- Setting up the MongoDB Java Driver
- Connecting to MongoDB
- Performing CRUD Operations
- Using Aggregation Framework
- Practical Exercises
- Setting up the MongoDB Java Driver
To interact with MongoDB from a Java application, you need to include the MongoDB Java Driver in your project. We will use Maven for dependency management.
Maven Dependency
Add the following dependency to your pom.xml
file:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.4.0</version> </dependency>
Gradle Dependency
If you are using Gradle, add the following to your build.gradle
file:
- Connecting to MongoDB
To connect to a MongoDB instance, you need to create a MongoClient
object. Here is an example of how to connect to a local MongoDB instance:
import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; public class MongoDBConnection { public static void main(String[] args) { // Create a MongoClient object MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); // Access the database MongoDatabase database = mongoClient.getDatabase("mydatabase"); System.out.println("Connected to the database successfully"); } }
Explanation
MongoClients.create("mongodb://localhost:27017")
: Creates a new MongoClient instance connected to the MongoDB server running onlocalhost
at port27017
.mongoClient.getDatabase("mydatabase")
: Accesses the database namedmydatabase
.
- Performing CRUD Operations
Creating Documents
To insert a document into a collection, use the insertOne
method.
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class CreateDocument { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); Document document = new Document("name", "John Doe") .append("age", 30) .append("city", "New York"); collection.insertOne(document); System.out.println("Document inserted successfully"); } }
Reading Documents
To read documents from a collection, use the find
method.
import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; public class ReadDocuments { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); FindIterable<Document> documents = collection.find(); for (Document doc : documents) { System.out.println(doc.toJson()); } } }
Updating Documents
To update a document, use the updateOne
method.
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; public class UpdateDocument { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); collection.updateOne(Filters.eq("name", "John Doe"), Updates.set("age", 31)); System.out.println("Document updated successfully"); } }
Deleting Documents
To delete a document, use the deleteOne
method.
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.client.model.Filters; public class DeleteDocument { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); collection.deleteOne(Filters.eq("name", "John Doe")); System.out.println("Document deleted successfully"); } }
- Using Aggregation Framework
The aggregation framework allows you to perform complex data processing and transformation operations.
import com.mongodb.client.AggregateIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class AggregationExample { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); AggregateIterable<Document> result = collection.aggregate(Arrays.asList( new Document("$match", new Document("city", "New York")), new Document("$group", new Document("_id", "$city") .append("averageAge", new Document("$avg", "$age"))) )); for (Document doc : result) { System.out.println(doc.toJson()); } } }
Explanation
$match
: Filters documents to include only those where thecity
is "New York".$group
: Groups the documents bycity
and calculates the average age.
- Practical Exercises
Exercise 1: Insert Multiple Documents
Write a Java program to insert multiple documents into a MongoDB collection.
Solution:
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.Arrays; public class InsertMultipleDocuments { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); Document doc1 = new Document("name", "Alice").append("age", 25).append("city", "Los Angeles"); Document doc2 = new Document("name", "Bob").append("age", 28).append("city", "Chicago"); collection.insertMany(Arrays.asList(doc1, doc2)); System.out.println("Documents inserted successfully"); } }
Exercise 2: Find Documents with a Specific Condition
Write a Java program to find all documents where the age is greater than 25.
Solution:
import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.client.model.Filters; public class FindDocuments { public static void main(String[] args) { MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017"); MongoDatabase database = mongoClient.getDatabase("mydatabase"); MongoCollection<Document> collection = database.getCollection("mycollection"); FindIterable<Document> documents = collection.find(Filters.gt("age", 25)); for (Document doc : documents) { System.out.println(doc.toJson()); } } }
Conclusion
In this section, we covered how to set up the MongoDB Java Driver, connect to a MongoDB instance, and perform CRUD operations. We also explored the aggregation framework and provided practical exercises to reinforce the learned concepts. In the next module, we will delve into building real-world applications using MongoDB.