Docs Menu
Docs Home
/ / /
Java Sync Driver
/ / /

Bulk Operations

On this page

  • Overview
  • Performing Bulk Operations
  • Insert Operation
  • Replace Operation
  • Update Operation
  • Delete Operation
  • Order of Execution
  • Ordered Execution
  • Unordered Execution
  • Summary

In this guide, you can learn how to use bulk operations in the MongoDB Java Driver.

To perform a create, replace, update, or delete operation, use its corresponding method. For example, to insert one document, update multiple documents, and delete one document in your collection, use the insertOne(), updateMany() and deleteOne() methods.

The MongoClient performs these operations by making a call for each operation to the database. You can reduce the number of calls to the database to one by using bulk operations.

Bulk operations consist of a large number of write operations. To perform a bulk operation, pass a List of WriteModel documents to the bulkWrite() method. A WriteModel is a model that represents any of the write operations.

The following sections show how to create and use each WriteModel document. The examples in each section use the following documents in the people collection:

{ "_id": 1, "name": "Karen Sandoval", "age": 31 }
{ "_id": 2, "name": "William Chin", "age": 54 }
{ "_id": 8, "name": "Shayla Ray", "age": 20 }

For more information about the methods and classes mentioned in this section, see the following API Documentation:

  • bulkWrite()

  • WriteModel

  • BulkWriteOptions

To perform an insert operation, create an InsertOneModel specifying the document you want to insert. To insert multiple documents, you must create an InsertOneModel for each document you want to insert.

The following example creates an InsertOneModel for two documents describing people:

InsertOneModel<Document> juneDoc = new InsertOneModel<>(new Document("name", "June Carrie")
.append("age", 17));
InsertOneModel<Document> kevinDoc = new InsertOneModel<>(new Document("name", "Kevin Moss")
.append("age", 22));

Important

When performing a bulkWrite(), the InsertOneModel cannot insert a document with an _id that already exists in the collection. Instead, the method throws a MongoBulkWriteException.

The following example tries to insert two documents where the _id is 1 and 3:

try {
List<WriteModel<Document>> bulkOperations = new ArrayList<>();
// Creates instructions to insert documents
InsertOneModel<Document> doc1 = new InsertOneModel<>(new Document("_id", 1));
InsertOneModel<Document> doc3 = new InsertOneModel<>(new Document("_id", 3));
bulkOperations.add(doc1);
bulkOperations.add(doc3);
// Runs a bulk write operation for the specified insert WriteModels
collection.bulkWrite(bulkOperations);
// Prints a message if any exceptions occur during the bulk write operation
} catch (MongoBulkWriteException e){
System.out.println("A MongoBulkWriteException occurred with the following message: " + e.getMessage());
}

The following shows the output of the preceding code:

A MongoBulkWriteException occurred with the following message:
Bulk write operation error on server sample-shard-00-02.pw0q4.mongodb.net:27017.
Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key
error collection: crudOps.bulkWrite index: _id_ dup key: { _id: 1 }', details={}}].

To see why the document with the _id of 3 didn't insert, see the Order of Execution section.

For more information about the methods and classes mentioned in this section, see the InsertOneModel API Documentation.

To perform a replace operation, create a ReplaceOneModel specifying a query filter for the document you want to replace with the replacement document.

Important

When performing a bulkWrite(), the ReplaceOneModel cannot make changes to a document that violate unique index constraints on the collection, and the model does not replace a document if there are no matches to your query filter.

The following example creates a ReplaceOneModel to replace a document where the _id is 1 with a document that contains an added location field:

ReplaceOneModel<Document> celineDoc = new ReplaceOneModel<>(
Filters.eq("_id", 1),
new Document("name", "Celine Stork")
.append("location", "San Diego, CA"));

For more information about the methods and classes mentioned in this section, see the following resources:

To perform an update operation, create an UpdateOneModel or an UpdateManyModel specifying a query filter for documents you want to update with what the updates are.

The UpdateOneModel updates the first document that matches your query filter and the UpdateManyModel updates all the documents that match your query filter.

Important

When performing a bulkWrite(), the UpdateOneModel and UpdateManyModel cannot make changes to a document that violate unique index constraints on the collection, and the models do not update any documents if there are no matches to your query filter.

The following example creates an UpdateOneModel to update the age field in a document where the _id is 2:

UpdateOneModel<Document> updateDoc = new UpdateOneModel<>(
Filters.eq("_id", 2),
Updates.set("age", 31));

For more information about the methods and classes mentioned in this section, see the following resources:

To perform a delete operation, create a DeleteOneModel or a DeleteManyModel specifying a query filter for documents you want to delete.

The DeleteOneModel deletes the first document that matches your query filter and the DeleteManyModel deletes all the documents that match your query filter.

Important

When performing a bulkWrite(), the DeleteOneModel and DeleteManyModel do not delete any documents if there are no matches to your query filter.

The following example creates a DeleteOneModel to delete a document where the _id is 1:

DeleteOneModel<Document> deleteDoc = new DeleteOneModel<>(Filters.eq("_id", 1));

For more information about the methods and classes mentioned in this section, see the following API Documentation:

The bulkWrite() method accepts an optional BulkWriteOptions as a second parameter to specify whether the execution of the bulk operations is ordered or unordered.

By default, the bulkWrite() method executes bulk operations in order. This means that the bulk operations execute in the order you added them to the list until an error occurs, if any.

The following example performs these bulk operations:

  • An operation that inserts a document with a name value of "Zaynab Omar" and an age value of 37

  • An operation that replaces the document where the _id is 1 with a new document that contains the location field

  • An operation that updates the document with a name value of "Zaynab Omar" and changes the name to "Zaynab Hassan"

  • An operation that deletes all documents where the age value is greater than 50

List<WriteModel<Document>> bulkOperations = new ArrayList<>();
// Creates instructions to insert a document
InsertOneModel<Document> insertDoc = new InsertOneModel<>(new Document("_id", 6)
.append("name", "Zaynab Omar")
.append("age", 37));
// Creates instructions to replace the first document matched by the query
ReplaceOneModel<Document> replaceDoc = new ReplaceOneModel<>(Filters.eq("_id", 1),
new Document("name", "Sandy Kane")
.append("location", "Helena, MT"));
// Creates instructions to update the first document matched by the query
UpdateOneModel<Document> updateDoc = new UpdateOneModel<>(Filters.eq("name", "Zaynab Omar"),
Updates.set("name", "Zaynab Hassan"));
// Creates instructions to delete all documents matched by the query
DeleteManyModel<Document> deleteDoc = new DeleteManyModel<>(Filters.gt("age", 50));
bulkOperations.add(insertDoc);
bulkOperations.add(replaceDoc);
bulkOperations.add(updateDoc);
bulkOperations.add(deleteDoc);
// Runs a bulk write operation for the specified the insert, replace, update, and delete WriteModels in order
collection.bulkWrite(bulkOperations);

After running this example, your collection contains the following document:

{ "_id": 1, "name": "Sandy Kane", "location": "Helena, MT" }
{ "_id": 8, "name": "Shayla Ray", "age": 20 }
{ "_id": 6, "name": "Zaynab Hassan", "age": 37 }

You can also execute bulk operations in any order by specifying "false" to the order() method on BulkWriteOptions. This means that all the write operations execute regardless of errors and if any errors occur the bulk operation reports them at the end.

Adding to the preceding example, including the following specifies the bulk operations to execute in any order:

BulkWriteOptions options = new BulkWriteOptions().ordered(false);
// Runs a bulk write operation for the specified insert, replace, update, and delete WriteModels in any order
collection.bulkWrite(bulkOperations, options);

Note

Unordered bulk operations do not guarantee order of execution. The order can differ from the way you list them to optimize the runtime.

In the preceding example, if the bulkWrite() method decided to perform the insert operation after the update operation, nothing changes with the update operation because the document does not exist at that point in time. Your collection then contains the following documents:

{ "_id": 1, "name": "Sandy Kane", "location": "Helena, MT" }
{ "_id": 8, "name": "Shayla Ray", "age": 20 }
{ "_id": 6, "name": "Zaynab Omar", "age": 37 }

For more information about the methods and classes mentioned in this section, see the following API Documentation:

To perform a bulk operation, you create and pass a list of WriteModel documents to the bulkWrite() method.

There are 6 different WriteModel documents: InsertOneModel, ReplaceOneModel, UpdateOneModel, UpdateManyModel, DeleteOneModel and DeleteManyModel.

There are two ways to execute the bulkWrite() method:

  • Ordered, which performs the bulk operations in order until an error occurs, if any

  • Unordered, which performs all the bulk operations in any order and reports errors at the end, if any

← Insert or Update in a Single Operation