🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
What You Will Learn:
- How to connect Java to MongoDB.
- How to perform Create, Read, Update, and Delete operations in MongoDB using Java.
- How to verify each operation in MongoDB.
Technologies Used:
- JDK: Version 21
- MongoDB: Version 6.0 or later
- MongoDB Java Driver: Version 5.1.4
Step 1: Add MongoDB Java Driver Dependency
To perform CRUD operations, add the MongoDB Java Driver to your project.
For Maven Users:
Add the following dependency to your pom.xml file:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>5.1.4</version>
</dependency>
For Gradle Users:
Add the following line to your build.gradle file:
implementation 'org.mongodb:mongodb-driver-sync:5.1.4'
If you don't use Maven or Gradle, you can download the MongoDB Java Driver JAR file and manually add it to your classpath.
Step 2: Connect to MongoDB
First, establish a connection to your MongoDB database.
Code Example:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class MongoDBConnectionExample {
private static final String URI = "mongodb://localhost:27017";
public static void main(String[] args) {
// Connect to MongoDB server
try (MongoClient mongoClient = MongoClients.create(URI)) {
// Access the database
MongoDatabase database = mongoClient.getDatabase("mydb");
System.out.println("Connected to MongoDB database: " + database.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
- The
MongoClientestablishes the connection to MongoDB. - The
getDatabase("mydb")method accesses or creates a database namedmydb.
Step 3: Create (Insert a Document)
Let’s insert a document into a collection named employees.
Code Example:
import com.mongodb.client.MongoCollection;
import org.bson.Document;
public class MongoDBCreateExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create(URI)) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
// Create a new document
Document employee = new Document("name", "Raj")
.append("age", 30)
.append("department", "IT");
// Insert the document
collection.insertOne(employee);
System.out.println("Document inserted: " + employee.toJson());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
Documentrepresents the data to insert.insertOne()inserts the document into theemployeescollection.
Step 4: Read (Retrieve Documents)
Now, let's retrieve the documents from the employees collection.
Code Example:
import com.mongodb.client.MongoCursor;
import org.bson.Document;
public class MongoDBReadExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create(URI)) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
// Fetch all documents from the collection
MongoCursor<Document> cursor = collection.find().iterator();
// Iterate and print each document
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
collection.find()fetches all documents from theemployeescollection.- The
MongoCursoriterates through the documents and prints them.
Step 5: Update (Modify a Document)
Next, we update the department of an employee whose name is "Raj".
Code Example:
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
public class MongoDBUpdateExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create(URI)) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
// Update the department of an employee with name "Raj"
collection.updateOne(Filters.eq("name", "Raj"),
Updates.set("department", "Engineering"));
System.out.println("Document updated successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
Filters.eq()is used to find documents wherename = "Raj".Updates.set()modifies thedepartmentfield for the matching document.
Step 6: Delete (Remove a Document)
Finally, let’s delete an employee document named "Raj".
Code Example:
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.model.Filters;
public class MongoDBDeleteExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create(URI)) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
// Delete the document where the name is "Raj"
DeleteResult result = collection.deleteOne(Filters.eq("name", "Raj"));
if (result.getDeletedCount() > 0) {
System.out.println("Document deleted successfully.");
} else {
System.out.println("No document found with the specified criteria.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation:
deleteOne()deletes the first document that matches the filter condition.Filters.eq("name", "Raj")identifies the document to delete.
Step 7: Run and Test Each CRUD Operation
You can run each example as a standalone Java program or integrate all operations in one project. Use the MongoDB shell or a MongoDB client tool to verify the changes in the employees collection.
Shell Verification:
use mydb
db.employees.find()
Conclusion
In this tutorial, you learned how to:
- Connect Java 21 to MongoDB using the MongoDB Java Driver.
- Perform CRUD operations (Create, Read, Update, Delete) on a MongoDB collection.
- Verify the CRUD operations using the MongoDB shell.
This is a basic guide to performing essential MongoDB operations using Java. You can extend it by adding more advanced query filters, handling bulk operations, and implementing transactional operations.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment