Java MongoDB Replace a Document

In this tutorial, we will learn how to replace an existing document in a MongoDB collection using Java. Replacing a document means substituting the entire document with a new one. We'll use the MongoDB Java Driver to connect to MongoDB, replace the document, and verify the replacement.

What You Will Learn:

  • How to connect Java to MongoDB.
  • How to replace a document in a MongoDB collection.
  • How to verify the replaced document.

Technologies Used:

  • JDK: Version 21 (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 connect your Java application to MongoDB.

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 don't use Maven or Gradle, you can download the MongoDB Java Driver JAR file and manually add it to your classpath.

Step 2: Write Java Code to Replace a Document

Below is the Java code that connects to MongoDB and replaces an existing 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.Filters;

public class MongoDBReplaceDocumentExample {

    // 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 new document to replace the existing one
            Document newEmployee = new Document("name", "Raj")
                                    .append("age", 35)
                                    .append("department", "Engineering")
                                    .append("position", "Team Lead");

            // Step 5: Replace the document where "name" is "Raj"
            collection.replaceOne(
                Filters.eq("name", "Raj"), // Filter to find the document to replace
                newEmployee // The new document to replace the old one
            );

            // Step 6: Confirm document replacement
            System.out.println("Document replaced 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: Create a New Document A new Document object is created with updated information about the employee. This will replace the existing document where the employee's name is "Raj".

    Document newEmployee = new Document("name", "Raj")
                               .append("age", 35)
                               .append("department", "Engineering")
                               .append("position", "Team Lead");
    
  • Step 5: Replace the Existing Document The replaceOne() method replaces the entire document where the filter matches. In this case, it replaces the document where name = "Raj".

    collection.replaceOne(
        Filters.eq("name", "Raj"),
        newEmployee
    );
    
    • Filters.eq(): This is used to find the document to replace by filtering with the "name" field.
    • newEmployee: This is the new document that will completely replace the old one.
  • Step 6: Confirm Document Replacement A confirmation message is printed to the console indicating that the document was replaced.

    System.out.println("Document replaced 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 document was replaced successfully, you will see the following output:

Document replaced in the 'employees' collection.

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

Step 4: Verify the Replaced Document

You can use the MongoDB shell or any MongoDB client tool to verify the document replacement. In the MongoDB shell, use the following commands:

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

The replaced document should look like this:

{
    "_id" : ObjectId("someObjectId"),
    "name" : "Raj",
    "age" : 35,
    "department" : "Engineering",
    "position" : "Team Lead"
}

The entire document is replaced, so only the new fields specified in the replacement document are present.

Conclusion

In this tutorial, you learned how to:

  • Connect Java to MongoDB using the MongoDB Java Driver.
  • Replace a document in a MongoDB collection using the replaceOne() method.
  • Verify the replaced document using the MongoDB shell.

This approach is useful when you need to completely replace a document in a MongoDB collection with a new one. You can extend this functionality to handle more complex replacement scenarios, such as applying conditional logic to decide when to replace a document.

Comments