🎓 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 manually create a collection in MongoDB using Java.
- How to verify the collection creation.
Technologies Used:
- JDK: Version 21 or later (Recommended: Latest version)
- MongoDB: Version 6.0 or later
- MongoDB Java Driver: Version 5.1.4 (latest)
Step 1: Add MongoDB Java Driver Dependency
To connect your Java application to MongoDB, you need to include the MongoDB Java Driver.
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 are not using Maven or Gradle, download the MongoDB Java Driver JAR file and manually add it to your project classpath.
Step 2: Write Java Code to Create a Collection in MongoDB
Below is a simple Java program that connects to MongoDB and manually creates a collection.
Code Example:
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
public class MongoDBCreateCollectionExample {
// MongoDB connection URI
private static final String URI = "mongodb://localhost:27017";
public static void main(String[] args) {
// Step 1: Create a MongoClient instance to connect to MongoDB
try (MongoClient mongoClient = MongoClients.create(URI)) {
// Step 2: Access the database (it will create it if it doesn't exist)
MongoDatabase database = mongoClient.getDatabase("mydb");
// Step 3: Create a new collection
database.createCollection("employees");
// Step 4: Confirm collection creation
System.out.println("Collection 'employees' created successfully in database: " + database.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Explanation with Code Snippets:
Step 1: Create a MongoClient Instance The
MongoClientis used to establish a connection to the MongoDB server. The connection stringmongodb://localhost:27017is used to connect to MongoDB running on your local machine.try (MongoClient mongoClient = MongoClients.create(URI)) {Here, we wrap
MongoClientin a try-with-resources block to ensure that it closes automatically after use.Step 2: Access the Database The
getDatabase()method is used to connect to the database namedmydb. If themydbdatabase doesn't exist, MongoDB will automatically create it when you interact with it.MongoDatabase database = mongoClient.getDatabase("mydb");This returns a
MongoDatabaseobject that allows you to interact with themydbdatabase.Step 3: Create a Collection The
createCollection()method is used to manually create a collection in themydbdatabase. In this case, we are creating a collection namedemployees.database.createCollection("employees");This will explicitly create the
employeescollection if it doesn't already exist in the database.Step 4: Confirm Collection Creation After creating the collection, we print a confirmation message to the console. This confirms that the
employeescollection has been successfully created.System.out.println("Collection 'employees' created successfully in database: " + database.getName());
Step 3: Run the Java Program
After writing the code, you can run the program in your IDE or from the command line. If everything is set up correctly, the output will be:
Collection 'employees' created successfully in database: mydb
If there is an error, such as MongoDB not running or an incorrect URI, an error message will be displayed.
Step 4: Verify the Collection in MongoDB
You can verify the collection creation using the MongoDB shell or a MongoDB client tool. In the MongoDB shell, use the following command:
use mydb
show collections
You should see employees in the list of collections.
Conclusion
In this tutorial, you learned how to:
- Connect Java to MongoDB using the MongoDB Java Driver.
- Manually create a collection in MongoDB.
- Verify the collection creation using the MongoDB shell.
This example demonstrates how to manually create a collection, which can be helpful when you want to define specific configurations for your collections or when organizing your data.
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