Course – LS – All

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

>> CHECK OUT THE COURSE

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 implementation of all these examples and code snippets can be found over on GitHub.

Course – LSD (cat=Persistence)

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

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.