Java MongoDB Create or Insert Document Example Tutorial

In this tutorial, we will learn how to insert a document into a MongoDB collection using Java. MongoDB uses collections to store documents, and inserting data into these collections is a core operation. We'll use the MongoDB Java Driver to connect to MongoDB and perform the insert operation.

What You Will Learn:

  • How to connect Java to MongoDB.
  • How to insert a document into a MongoDB collection.
  • How to verify the inserted document.

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

You need to 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 are not using Maven or Gradle, download the MongoDB Java Driver JAR file and add it to your classpath manually.

Step 2: Write Java Code to Insert a Document

Here’s a simple Java program that connects to MongoDB and inserts a document into a collection.

Code Example:

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

public class MongoDBInsertDocumentExample {

    // 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: Access the collection (it will create it if it doesn't exist)
            MongoCollection<Document> collection = database.getCollection("employees");

            // Step 4: Create a document to insert
            Document employee = new Document("name", "Raj")
                                    .append("age", 30)
                                    .append("department", "IT");

            // Step 5: Insert the document into the collection
            collection.insertOne(employee);

            // Step 6: Confirm document insertion
            System.out.println("Document inserted into the 'employees' collection.");
            
        } 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 locally on port 27017.

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

    Using a try-with-resources block ensures the MongoClient is automatically closed after use.

  • Step 2: Access the Database Use the getDatabase() method to access the mydb database. If the database does not exist, MongoDB will create it automatically when needed.

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

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

  • Step 3: Access the Collection Use the getCollection() method to access the employees collection. If the collection does not exist, MongoDB will create it automatically when the first document is inserted.

    MongoCollection<Document> collection = database.getCollection("employees");
    

    This returns a MongoCollection<Document> object for interacting with the employees collection.

  • Step 4: Create a Document Create a Document object to represent the data you want to insert. In this example, we’re inserting an employee document with fields for name, age, and department.

    Document employee = new Document("name", "Raj")
                            .append("age", 30)
                            .append("department", "IT");
    

    The Document class is used to represent MongoDB documents in Java.

  • Step 5: Insert the Document The insertOne() method inserts a single document into the collection. Here, we are inserting the employee document into the employees collection.

    collection.insertOne(employee);
    
  • Step 6: Confirm Document Insertion Print a confirmation message to the console to indicate that the document was successfully inserted into the collection.

    System.out.println("Document inserted into the 'employees' collection.");
    

Step 3: Run the Java Program

After writing the code, run the program in your IDE or from the command line. If everything is set up correctly, you should see the following output:

Document inserted into the 'employees' collection.

If there is an issue, such as MongoDB not running or a connection problem, you will see an error message.

Step 4: Verify the Inserted Document

To confirm that the document was inserted, you can use the MongoDB shell or any MongoDB client tool. In the MongoDB shell, use the following commands:

use mydb
db.employees.find()

You should see the inserted document in the output, which should look like this:

{ "_id" : ObjectId("someObjectId"), "name" : "Raj", "age" : 30, "department" : "IT" }

Conclusion

In this tutorial, you learned how to:

  • Connect Java to MongoDB using the MongoDB Java Driver.
  • Insert a document into a MongoDB collection.
  • Verify the insertion of a document in the MongoDB shell.

This simple example can be expanded by adding more fields to the documents or performing bulk insertions. You can also use this approach to build more complex applications that require interaction with MongoDB from Java.

Comments