MongoDB CRUD Tutorials in Java: A Step-by-Step Guide
In this tutorial, we will guide you through the process of performing CRUD (Create, Read, Update, Delete) operations in MongoDB using Java.
MongoDB is a popular NoSQL database known for its flexibility and scalability. In this tutorial, we will guide you through the process of performing CRUD (Create, Read, Update, Delete) operations in MongoDB using Java. We’ll provide step-by-step instructions and practical examples with detailed explanations.
Prerequisites
Before you begin, make sure you have the following prerequisites in place:
-
Java Development Kit (JDK): Ensure you have Java installed on your system. You can download it from the official Oracle website or use an open-source alternative like OpenJDK.
-
Integrated Development Environment (IDE): Choose an IDE like Eclipse, IntelliJ IDEA, or NetBeans to write and manage your Java code.
-
MongoDB: You need to have MongoDB installed and running. You can download and install MongoDB from the official MongoDB website or use a package manager if you’re on a Linux system.
-
MongoDB Java Driver: You’ll need the MongoDB Java driver to connect to MongoDB from your Java application. You can include it in your project using a build tool like Maven or Gradle.
Step 1: Create a MongoDB Database
Let’s start by creating a MongoDB database where we will perform CRUD operations. Open your MongoDB client or use the command-line tool and execute the following commands:
# Start the MongoDB shell
mongo
# Create a new database
use mydb
This code will create a new database named mydb
.
Step 2: Set Up a Java Project
-
Open your preferred IDE and create a new Java project.
-
Add the MongoDB Java driver dependency to your project’s build file (e.g., Maven’s
pom.xml
or Gradle’sbuild.gradle
).
For Maven, add the following dependency:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.2</version>
</dependency>
For Gradle, add the following dependency:
implementation group: 'org.mongodb', name: 'mongodb-driver-sync', version: '4.4.2'
Step 3: Perform CRUD Operations
Create Operation (Insert)
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDBCRUDExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
Document document = new Document("first_name", "John")
.append("last_name", "Doe")
.append("age", 30);
collection.insertOne(document);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code inserts a new employee document into the employees
collection in the mydb
database.
Read Operation (Find)
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class MongoDBCRUDExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
Document document = cursor.next();
System.out.println(document.toJson());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code retrieves and prints all employee documents from the employees
collection.
Update Operation (Update)
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
public class MongoDBCRUDExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
collection.updateOne(
Filters.eq("first_name", "John"),
Updates.set("age", 31)
);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code updates the age of the employee named “John” in the employees
collection.
Delete Operation (Delete)
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
public class MongoDBCRUDExample {
public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database =
mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = database.getCollection("employees");
collection.deleteOne(Filters.eq("first_name", "John"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code deletes the employee named “John” from the employees
collection.
Conclusion
In this tutorial, you’ve learned how to perform CRUD operations in MongoDB using Java. You created a MongoDB database, set up a Java project, and wrote code for Create, Read, Update, and Delete operations with detailed explanations. MongoDB’s flexibility and scalability make it a great choice for various types of applications. As you continue your journey in Java development and MongoDB, you can build more complex and feature-rich applications based on these fundamentals. Happy coding!