Docs Menu

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 contain the following documents in a collection:

{ "_id": 1 }
{ "_id": 2 }

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

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 where the _id values are "3" and "4":

InsertOneModel<Document> doc1 = new InsertOneModel<>(new Document("_id", 3));
InsertOneModel<Document> doc2 = new InsertOneModel<>(new Document("_id", 4));
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<>();
InsertOneModel<Document> doc3 = new InsertOneModel<>(new Document("_id", 1));
InsertOneModel<Document> doc4 = new InsertOneModel<>(new Document("_id", 3));
bulkOperations.add(doc3);
bulkOperations.add(doc4);
collection.bulkWrite(bulkOperations);
} catch (MongoBulkWriteException e){
System.out.println("A MongoBulkWriteException occured 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 additional field:

ReplaceOneModel<Document> doc3 = new ReplaceOneModel<>(
Filters.eq("_id", 1),
new Document("_id", 1).append("x", 4));

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 a document where the _id is "2" to a document that contains an additional field:

UpdateOneModel<Document> doc3 = new UpdateOneModel<>(
Filters.eq("_id", 2),
Updates.set("x", 8));

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> doc3 = 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 if you want to execute the bulk operations as 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 insert operation for a document where the _id is "3"
  • A replace operation for a document where the _id is "1" with a document that contains an additional field
  • An update operation for a document where the _id is "3" to a document that contains an additional field
  • A delete operation for all documents that contain the field x with the value "2"
List<WriteModel<Document>> bulkOperations = new ArrayList<>();
InsertOneModel<Document> doc1 = new InsertOneModel<>(new Document("_id", 3));
ReplaceOneModel<Document> doc2 = new ReplaceOneModel<>(Filters.eq("_id", 1),
new Document("_id", 1).append("x", 2));
UpdateOneModel<Document> doc3 = new UpdateOneModel<>(Filters.eq("_id", 3), Updates.set("x", 2));
DeleteManyModel<Document> doc4 = new DeleteManyModel<>(Filters.eq("x", 2));
bulkOperations.add(doc1);
bulkOperations.add(doc2);
bulkOperations.add(doc3);
bulkOperations.add(doc4);
collection.bulkWrite(bulkOperations);

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

{ "_id": 2 }

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);
collection.bulkWrite(bulkOperations, options);
Note

Unordered bulk operations do not guarantee order of execution. The order may 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": 2 }
{ "_id": 3 }

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 OperationSpecify a Query →
Give Feedback
© 2022 MongoDB, Inc.

About

  • Careers
  • Investor Relations
  • Legal Notices
  • Privacy Notices
  • Security Information
  • Trust Center
© 2022 MongoDB, Inc.