Java MongoDB Update Document Example

In this tutorial, we will walk through how to update a document in a MongoDB collection using Java. MongoDB allows you to update specific fields within documents or replace the entire document. We’ll use the MongoDB Java Driver to connect to the database, update a document, and verify the update.

What You Will Learn:

  • How to connect Java to MongoDB.
  • How to update a document in a MongoDB collection.
  • How to verify the updated document.

Technologies Used:

  • JDK: Version 1.8 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 add 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 classpath.

Step 2: Write Java Code to Update a Document

Here’s a simple Java program that connects to MongoDB and updates a document in a collection.

Code Example:

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

public class MongoDBUpdateDocumentExample {

    // 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: Update a document
            collection.updateOne(
                Filters.eq("name", "Raj"), // Filter to find the document
                Updates.set("department", "Engineering") // Update the department field
            );

            // Step 5: Confirm document update
            System.out.println("Document updated in 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 MongoDB using the connection string mongodb://localhost:27017.

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

    This block ensures the client is closed automatically after the operation is complete.

  • 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.

    MongoDatabase database = mongoClient.getDatabase("mydb");
    
  • Step 3: Access the Collection Use getCollection() to access the employees collection. MongoDB will create this collection if it does not already exist.

    MongoCollection<Document> collection = database.getCollection("employees");
    
  • Step 4: Update the Document The updateOne() method is used to update a single document. Here we are finding a document where name = "Raj" and updating the department field to "Engineering".

    collection.updateOne(
        Filters.eq("name", "Raj"),
        Updates.set("department", "Engineering")
    );
    
    • Filters.eq(): This is used to specify the document you want to update by filtering with a specific field (in this case, "name": "Raj").
    • Updates.set(): This is used to update the value of a specific field (in this case, updating "department": "Engineering").
  • Step 5: Confirm Document Update Print a confirmation message to the console indicating that the document has been updated.

    System.out.println("Document updated in 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 the update was successful, you will see the following output:

Document updated in the 'employees' collection.

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

Step 4: Verify the Updated Document

To verify the updated document, use the MongoDB shell or a MongoDB client tool. In the MongoDB shell, you can use the following commands:

use mydb
db.employees.find({ "name": "Raj" })

The updated document should look like this:

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

The department field should now show "Engineering".

Conclusion

In this tutorial, you learned how to:

  • Connect Java to MongoDB using the MongoDB Java Driver.
  • Update a document in a MongoDB collection using the updateOne() method.
  • Verify the updated document using the MongoDB shell.

This basic example demonstrates how to perform updates in MongoDB. You can expand it by using other update methods, such as updateMany(), or by applying more complex filters and updates to your documents.

Comments