Java MongoDB CRUD Operations

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 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 (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this tutorial, you will learn how to perform basic CRUD (Create, Read, Update, Delete) operations on a MongoDB collection using Java. We'll use the MongoDB Java Driver to connect to MongoDB and demonstrate these four operations with code examples.

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 MongoClient establishes the connection to MongoDB.
  • The getDatabase("mydb") method accesses or creates a database named mydb.

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:

  • Document represents the data to insert.
  • insertOne() inserts the document into the employees collection.

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 the employees collection.
  • The MongoCursor iterates 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 where name = "Raj".
  • Updates.set() modifies the department field 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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare