Java MongoDB Create Collection Example

In this tutorial, you will learn how to manually create a collection in a MongoDB database using Java. MongoDB typically creates collections automatically when you insert data, but you can create collections manually as needed.

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 MongoClient is used to establish a connection to the MongoDB server. The connection string mongodb://localhost:27017 is used to connect to MongoDB running on your local machine.

    try (MongoClient mongoClient = MongoClients.create(URI)) {
    

    Here, we wrap MongoClient in 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 named mydb. If the mydb database doesn't exist, MongoDB will automatically create it when you interact with it.

    MongoDatabase database = mongoClient.getDatabase("mydb");
    

    This returns a MongoDatabase object that allows you to interact with the mydb database.

  • Step 3: Create a Collection The createCollection() method is used to manually create a collection in the mydb database. In this case, we are creating a collection named employees.

    database.createCollection("employees");
    

    This will explicitly create the employees collection 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 employees collection 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.

Comments