Batch update documents in MongoDB using Java
This article is about performing bulk updates of documents in MongoDB using the Java driver. We will also learn how to update by adding new fields, changing the value of an existing field or array, or deleting documents.
Prerequisites
For this article, we will use the following tools that you must follow.
Batch update documents in MongoDB using Java
Bulk updates are useful when we need to update multiple documents in the database. Now, the question is, how do we update the documents?
Do we want to update by adding new fields, updating the value of an existing field or array, or deleting a document? To understand all these scenarios, let's create a collection and insert two documents.
Create a collection:
db.createCollection('supervisor');
Insert the first document:
db.supervisor.insertOne(
{
"firstname": "Mehvish",
"lastname": "Ashiq",
"gender": "Female",
"contact" : {
"email":"mehvishofficial@gmail.com",
"phone" : [
{
"type" : "official",
"number" : "123456789"
},
{
"type" : "personal",
"number" : "124578369"
},
]
},
"entries" : [
{ "_id" : 1, "itemsperday" : [ 1,3,4,5,6,7 ] },
{ "_id" : 2, "itemperday" : [ 2,3,4,5,2,7 ] },
{ "_id" : 3, "itemperday" : [ 5,0,0,4,0,1 ] }
]
}
);
Insert the second file:
db.supervisor.insertOne(
{
"firstname": "Tahir",
"lastname": "Raza",
"gender": "Male",
"contact" : {
"email":"tahirraza@gmail.com",
"phone" : [
{
"type" : "official",
"number" : "123478789"
},
{
"type" : "personal",
"number" : "122378369"
},
]
},
"entries" : [
{ "_id" : 1, "itemsperday" : [ 4,5,6,7,4,6 ] },
{ "_id" : 2, "itemperday" : [ 2,3,2,7,5,2 ] },
{ "_id" : 3, "itemperday" : [ 5,0,0,1,0,0 ] }
]
}
);
After populating the collection, you can db.supervisor.find().pretty();
view the inserted documents using . We'll start with easy solutions and then move on to some tricky but interesting ones.
Use updateMany()
to perform bulk updates by adding new fields to existing documents
Sample code:
//write your package where you want to save your source file
package com.voidtesting.javamongobulkupdateexample;
// import necessary libraries
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
// Example_1
public class Example_1 {
// main method
public static void main(String[] args) {
// Replace the connection string with your own connection string
var uri = "mongodb://localhost:27017";
// try block
try ( MongoClient mongoClient = MongoClients.create(uri)) {
// print message if connection is successfully established
System.out.println("Connected successfully to server.");
// get the specified database from the MongoDB server
MongoDatabase database = mongoClient.getDatabase("bulkUpdate");
// get the specified collection from the selected database
MongoCollection<Document> collection = database.getCollection("supervisor");
// update documents by adding a new field and its value
collection.updateMany(new BasicDBObject(),
new BasicDBObject("$set",
new BasicDBObject("status", "Good")));
// print a new line
System.out.println();
// iterate over all documents of the selected collection
// to print in Java IDE
collection.find().forEach(doc -> {
System.out.println(doc.toBsonDocument());
System.out.println();
});// end forEach
} // end try block
// print error if unable to execute a command
catch (MongoException error) {
System.err.println("An error occurred while running a command: " + error);
}// end catch block
}// end main method
}//end Example_1
Output:
{
"_id": {"$oid": "62a866e592fd89ad9c4932ed"},
"firstname": "Mehvish",
"lastname": "Ashiq",
"gender": "Female",
"contact": {
"email": "mehvishofficial@gmail.com",
"phone": [
{ "type": "official", "number": "123456789"},
{"type": "personal", "number": "124578369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [1.0, 3.0, 4.0, 5.0, 6.0, 7.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 4.0, 5.0, 2.0, 7.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 4.0, 0.0, 1.0]}
],
"status": "Good"
}
{
"_id": {"$oid": "62a8670192fd89ad9c4932ee"},
"firstname": "Tahir",
"lastname": "Raza",
"gender": "Male",
"contact": {
"email": "tahirraza@gmail.com",
"phone": [
{"type": "official", "number": "123478789"},
{"type": "personal", "number": "122378369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [4.0, 5.0, 6.0, 7.0, 4.0, 6.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 2.0, 7.0, 5.0, 2.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 1.0, 0.0, 0.0]}
],
"status": "Good"
}
We have formatted the output for you (as shown above), but you will see one document per line on the IDE. We can also db.supervisor.find().pretty();
view the updated documents on the mongo shell using .
For this sample code, we use updateMany()
the update method of the mongo collection object, which accepts filter
a query and update
statement to update the matching documents. Here, instead of filtering the documents, we add a status
new field called update to all the existing documents (see the output given above).
updateMany()
Perform a batch update of existing fields in multiple documents matching the filter
using
Sample code:
//write your package where you want to save your source file
package com.voidtesting.javamongobulkupdateexample;
// import necessary libraries
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.combine;
import static com.mongodb.client.model.Updates.set;
import org.bson.Document;
// Example_2
public class Example_2 {
// main method
public static void main(String[] args) {
// Replace the connection string with your own connection string
var uri = "mongodb://localhost:27017";
// try block
try ( MongoClient mongoClient = MongoClients.create(uri)) {
// print message if connection is successfully established
System.out.println("Connected successfully to server.");
// get the specified database from the MongoDB server
MongoDatabase database = mongoClient.getDatabase("bulkUpdate");
// get the specified collection from the selected database
MongoCollection<Document> collection = database.getCollection("supervisor");
// update the filtered documents by updating the existing field
collection.updateMany(eq("gender", "Female"),combine(set("gender", "F")));
collection.updateMany(eq("gender", "Male"),combine(set("gender", "M")));
System.out.println();
// iterate over all documents of the selected collection
// to print in Java IDE
collection.find().forEach(doc -> {
System.out.println(doc.toBsonDocument());
System.out.println();
});// end forEach
} // end try block
// print error if unable to execute a command
catch (MongoException error) {
System.err.println("An error occurred while running a command: " + error);
}// end catch block
}// end main method
}//end Example_2
Output:
{
"_id": {"$oid": "62a866e592fd89ad9c4932ed"},
"firstname": "Mehvish",
"lastname": "Ashiq",
"gender": "F",
"contact": {
"email": "mehvishofficial@gmail.com",
"phone": [
{ "type": "official", "number": "123456789"},
{"type": "personal", "number": "124578369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [1.0, 3.0, 4.0, 5.0, 6.0, 7.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 4.0, 5.0, 2.0, 7.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 4.0, 0.0, 1.0]}
],
"status": "Good"
}
{
"_id": {"$oid": "62a8670192fd89ad9c4932ee"},
"firstname": "Tahir",
"lastname": "Raza",
"gender": "M",
"contact": {
"email": "tahirraza@gmail.com",
"phone": [
{"type": "official", "number": "123478789"},
{"type": "personal", "number": "122378369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [4.0, 5.0, 6.0, 7.0, 4.0, 6.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 2.0, 7.0, 5.0, 2.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 1.0, 0.0, 0.0]}
],
"status": "Good"
}
This code example is similar to the previous one, but we are updating the value of a specific field in all documents that match the filter.
We use updateMany()
to perform a bulk update on all documents gender
where equal to Female
and gender
equal to . We change and to and , respectively .Male
"gender": "Female"
"gender": "Male"
"gender":"F"
"gender":"M"
So far, we have seen how to use updateMany()
the method to add new fields or update the value of existing fields at the first level. Next, we will learn how to use updateMany()
to perform a bulk update of embedded documents that satisfy a filter query.
updateMany()
Perform a batch update of embedded documents matching the filter
using
Sample code:
//write your package where you want to save your source file
package com.voidtesting.javamongobulkupdateexample;
// import necessary libraries
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.UpdateOptions;
import org.bson.Document;
import org.bson.conversions.Bson;
// Example_3
public class Example_3 {
// main method
public static void main(String[] args) {
// Replace the connection string with your own connection string
var uri = "mongodb://localhost:27017";
// try block
try ( MongoClient mongoClient = MongoClients.create(uri)) {
// print message if connection is successfully established
System.out.println("Connected successfully to server.");
// get the specified database from the MongoDB server
MongoDatabase database = mongoClient.getDatabase("bulkUpdate");
// get the specified collection from the selected database
MongoCollection<Document> collection = database.getCollection("supervisor");
// filter
Bson where = new Document().append("contact.phone.type", "official");
// update
Bson update = new Document().append("contact.phone.$.type", "assistant");
// set
Bson set = new Document().append("$set", update);
// update collection
collection.updateMany(where, set, new UpdateOptions());
// iterate over all documents of the selected collection
// to print in Java IDE
collection.find().forEach(doc -> {
System.out.println(doc.toBsonDocument());
System.out.println();
}); // end forEach
} // end try block
// print error if unable to execute a command
catch (MongoException error) {
System.err.println("An error occurred while running a command: " + error);
}// end catch block
}// end main method
}//end Example_3
Output:
{
"_id": {"$oid": "62a866e592fd89ad9c4932ed"},
"firstname": "Mehvish",
"lastname": "Ashiq",
"gender": "F",
"contact": {
"email": "mehvishofficial@gmail.com",
"phone": [
{ "type": "assistant", "number": "123456789"},
{"type": "personal", "number": "124578369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [1.0, 3.0, 4.0, 5.0, 6.0, 7.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 4.0, 5.0, 2.0, 7.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 4.0, 0.0, 1.0]}
],
"status": "Good"
}
{
"_id": {"$oid": "62a8670192fd89ad9c4932ee"},
"firstname": "Tahir",
"lastname": "Raza",
"gender": "M",
"contact": {
"email": "tahirraza@gmail.com",
"phone": [
{"type": "assistant", "number": "123478789"},
{"type": "personal", "number": "122378369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [4.0, 5.0, 6.0, 7.0, 4.0, 6.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 2.0, 7.0, 5.0, 2.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 1.0, 0.0, 0.0]}
],
"status": "Good"
}
In this Java program, we use updateMany()
the method to perform a batch update on the embedded documents that match the filter query.
Here, we update contact.phone.type
the value of from to . To access the array of documents, we use the positional operator ( ) to update the first array value that satisfies the filter query.official
assistant
$
When using the positional operator, we can also specify which array elements should be updated. We can specify the first, all, or a specific array element to be updated.
To specify an array element through the positional operator, we use dot notation
, a BSON
property access syntax for navigating an object. We use the positional operator in the following ways to update the first, all, or a specific array element.
Use bulkWrite()
the API to update existing documents that match a filter query
Sample code:
//write your package where you want to save your source file
package com.voidtesting.javamongobulkupdateexample;
// import necessary libraries
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.UpdateManyModel;
import com.mongodb.client.model.WriteModel;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
// Example_4
public class Example_4 {
// main method
public static void main(String[] args) {
// Replace the connection string with your own connection string
var uri = "mongodb://localhost:27017";
// try block
try ( MongoClient mongoClient = MongoClients.create(uri)) {
// print message if connection is successfully established
System.out.println("Connected successfully to server.");
// get the specified database from the MongoDB server
MongoDatabase database = mongoClient.getDatabase("bulkUpdate");
// get the specified collection from the selected database
MongoCollection<Document> collection = database.getCollection("supervisor");
// create object
List<WriteModel<Document>> writes = new ArrayList<>();
// delete the document matching the filter
writes.add(new DeleteOneModel<>(new Document("firstname", "Tahir")));
// update document matching the filter
writes.add(new UpdateManyModel<>(
new Document("status", "Good"), // filter
new Document("$set", new Document("status", "Excellent")) // update
));
// bulk write
collection.bulkWrite(writes);
// iterate over all documents of the selected collection
// to print in Java IDE
collection.find().forEach(doc -> {
System.out.println(doc.toBsonDocument());
System.out.println();
});// end forEach
} // end try block
catch (MongoException me) {
System.err.println("An error occurred while running a command: " + me);
}// end catch block
}// end main method
}// end Example_4
Output:
{
"_id": {"$oid": "62a866e592fd89ad9c4932ed"},
"firstname": "Mehvish",
"lastname": "Ashiq",
"gender": "F",
"contact": {
"email": "mehvishofficial@gmail.com",
"phone": [
{"type": "assistant", "number": "123456789"},
{"type": "personal", "number": "124578369"}
]
},
"entries": [
{"_id": 1.0, "itemsperday": [1.0, 3.0, 4.0, 5.0, 6.0, 7.0]},
{"_id": 2.0, "itemperday": [2.0, 3.0, 4.0, 5.0, 2.0, 7.0]},
{"_id": 3.0, "itemperday": [5.0, 0.0, 0.0, 4.0, 0.0, 1.0]}
],
"status": "Excellent"
}
In this example, we bulkWrite()
perform multiple operations (delete and update) at once using the API. DeleteOneModel()
for deleting documents matching the filter, while we use for UpdateManyModel()
updating the value of an existing field in all documents matching the filter.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
List all collections in MongoDB Shell
Publish Date:2025/04/29 Views:156 Category:MongoDB
-
When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c
Querying for non-null values in MongoDB
Publish Date:2025/04/29 Views:139 Category:MongoDB
-
This MongoDB article will explain how to query for non-null values in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers
Shutting down with code:100 error in MongoDB
Publish Date:2025/04/29 Views:53 Category:MongoDB
-
This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know
SELECT COUNT GROUP BY in MongoDB
Publish Date:2025/04/29 Views:74 Category:MongoDB
-
In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation
Differences between MongoDB and Mongoose
Publish Date:2025/04/29 Views:80 Category:MongoDB
-
This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s
Install MongoDB using Homebrew
Publish Date:2025/04/29 Views:161 Category:MongoDB
-
MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a
Create a MongoDB dump of the database
Publish Date:2025/04/29 Views:62 Category:MongoDB
-
In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t
Get the size of the database in MongoDB
Publish Date:2025/04/29 Views:88 Category:MongoDB
-
When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;
Grouping values by multiple fields with MongoDB
Publish Date:2025/04/29 Views:99 Category:MongoDB
-
MongoDB Group by Multiple Fields is used to group values by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per