eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

1. Overview

MongoDB is a document-oriented NoSQL database that is publicly available. We can update the documents in a collection using various methods like update, replace and save. In order to change a specific field of the document, we’ll use different operators like $set, $inc, etc.

In this tutorial, we’ll learn to modify the multiple fields of a document using the update and the replace query. For demonstration purposes, we’ll first discuss the mongo shell query and then its corresponding implementation in Java.

Let’s now look into the various methods to achieve the purpose.

2. Shell Query to Update Different Fields

Before we start, let us first create a new database, baeldung, and a sample collection, employee. We’ll use this collection in all the examples:

use baeldung;
db.createCollection(employee);

Let’s now add a few documents into this collection using the insertMany query:

db.employee.insertMany([
    {
        "employee_id": 794875,
        "employee_name": "David Smith",
        "job": "Sales Representative",
        "department_id": 2,
        "salary": 20000,
        "hire_date": NumberLong("1643969311817")
    },
    {
        "employee_id": 794876,
        "employee_name": "Joe Butler",
        "job": "Sales Manager",
        "department_id": 3,
        "salary": 30000,
        "hire_date": NumberLong("1645338658000")
    }
]);

As a result, we’ll get a JSON with ObjectId for both the documents as shown below:

{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("6211e034b76b996845f3193d"),
        ObjectId("6211e034b76b996845f3193e")
        ]
}

So far, we have set up the required environment. Let’s now update the documents that we just inserted.

2.1. Update Multiple Fields of a Single Document

We can use $set and $inc operators to update any field in MongoDB. The $set operator will set the newly specified value while the $inc operator will increase the value by a specified value.

Let’s first look into the MongoDB query to update two fields of the employee collection using the $set operator:

db.employee.updateOne(
    {
        "employee_id": 794875,
        "employee_name": "David Smith"
    },
    {
        $set:{
            department_id:3,
            job:"Sales Manager"
        }
    }
);

In the above query, the employee_id and employee_name field is used to filter the document and the $set operator is used to update the job and department_id fields.

We can also use the $set and $inc operators together in a single update query:

db.employee.updateOne(
    {
        "employee_id": 794875
    },
    {
        $inc: {
            department_id: 1
        },
        $set: {
            job: "Sales Manager"
        }
    }
);

This will update the job field to Sales Manager and increase the department_id by 1.

2.2. Update Multiple Fields of Multiple Documents

In addition, we can also update multiple fields of more than one document in MongoDB. We simply need to include the option multi:true to modify all documents that match the filter query criteria:

db.employee.update(
    {
        "job": "Sales Representative"
    },
    {
        $inc: { 
            salary: 10000
        }, 
        $set: { 
            department_id: 5
        }
    },
    {
        multi: true 
    }
);

Alternatively, we’ll get the same results using the updateMany query:

db.employee.updateMany(
    {
        "job": "Sales Representative"
    },
    {
        $inc: {
            salary: 10000
        },
        $set: {
            department_id: 5
        }
    }
);

In the above query, we used the updateMany method to update more than 1 document of the collection.

2.3. Common Problem While Updating Multiple Fields

So far, we have learned to update multiple fields using the update query by providing two different operators or using a single operator on multiple fields.

Now, if we use an operator multiple times with different fields in a single query, MongoDB will only update the last statement of the update query and ignore the rest:

db.employee.updateMany(
    {
        "employee_id": 794875
    },
    {
        $set: {
            department_id: 3
        },
        $set: {
            job:"Sales Manager"
        }
    }
);

The above query will return a similar output to this:

{
    "acknowledged":true,
    "matchedCount":1,
    "modifiedCount":1
}

In this case, the only job will be updated to “Sales Manager”. The department_id value will not be updated to 3.

3. Update Fields with Java Driver

So far, we have discussed the raw MongoDB queries. Let’s now perform the same operations using Java. MongoDB Java driver supports two classes to represent a MongoDB document, com.mongodb.BasicDBObject and org.bson.Document. We’ll look into both methods to update fields in a document.

Before we proceed, let’s first connect to the employee collection inside the baeldung DB:

MongoClient mongoClient = new MongoClient(new MongoClientURI("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection<Document> collection = database.getCollection("employee");

Here we’ve assumed that the MongoDB is running locally at the default port of 27017.

3.1. Using DBObject

In order to create the document in MongoDB, we’ll use the com.mongodb.DBObject interface and its implementation class com.mongodb.BasicDBObject.

The implementation of the DBObject is based on key-value pairs. The BasicDBObject is inherited from the LinkedHashMap class which is in the util package.

Let’s now use the com.mongodb.BasicDBObject to perform the update operation on multiple fields:

BasicDBObject searchQuery = new BasicDBObject("employee_id", 794875);
BasicDBObject updateFields = new BasicDBObject();
updateFields.append("department_id", 3);
updateFields.append("job", "Sales Manager");
BasicDBObject setQuery = new BasicDBObject();
setQuery.append("$set", updateFields);
UpdateResult updateResult = collection.updateMany(searchQuery, setQuery);

Here, first, we created a filter query on the basis of the employee_id. This operation will return a set of documents. Further, we’ve updated the value of the department_id and job according to the set query.

3.2. Using bson Document

We can perform all the MongoDB operations using the bson document. For that, first, we need the collection object and then perform the update operation using the updateMany method with the filter and set functions.

UpdateResult updateQueryResult = collection.updateMany(Filters.eq("employee_id", 794875),
Updates.combine(Updates.set("department_id", 3), Updates.set("job", "Sales Manager")));

Here, we are passing a query filter to the updateMany method. The eq filter matches employee_id with the exact matching text ‘794875’. Then, we update the department_id and the job using the set operator.

4. Using Replace Query

The naive approach to update the multiple fields of a document is to replace it with a new document that has updated values.

For example, if we wish to replace a document with employee_id 794875, we can execute the following query:

db.employee.replaceOne(
    {
        "employee_id": 794875
    },
    {
        "employee_id": 794875,
        "employee_name": "David Smith",
        "job": "Sales Manager",
        "department_id": 3,
        "salary": 30000,
        "hire_date": NumberLong("1643969311817")
    }
);

The above command will print an acknowledgment JSON in the output:

{
    "acknowledged":true,
    "matchedCount":1,
    "modifiedCount":1
}

Here, the employee_id field is used to filter the document. The second argument of the update query denotes the document from which the existing document will be replaced.

In the above query, we are performing replaceOne, hence, it will replace only a single document with that filter. Alternatively, if we want to replace all the documents with that filter query, then we would need to use the updateMany method.

5. Conclusion

In this article, we explored various ways to update multiple fields of a document in MongoDB. We broadly discussed two implementations, using MongoDB shell and using Java driver.

There are various options to update the multiple fields of a document including $inc and $set operators.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)