Docs Menu

Docs HomeJava Sync Driver

Perform Bulk Operations

The bulkWrite() method performs batch write operations against a single collection. This method reduces the number of network round trips from your application to your MongoDB instance which increases the performance of your application. Since you only receive the success status after all the operations return, we recommend you use this if that meets the requirements of your use case.

You can specify one or more of the following write operations in bulkWrite():

  • Insert a document

  • Update a document

  • Update multiple documents

  • Delete a document

  • Delete multiple documents

  • Replace a document

The bulkWrite() method accepts the following parameters:

  • A List of objects that implement WriteModel: the classes that implement WriteModel correspond to the preceding write operations. For example, the InsertOneModel class wraps the insertOne() write method, which inserts a document. See the links to the API documentation at the end of this page for more information about each class.

  • BulkWriteOptions: optional object that specifies settings such as whether to ensure your MongoDB instance orders your write operations.

Note

Retryable writes run on MongoDB Server versions 3.6 or later in bulk write operations unless they include one or more instances of UpdateManyModel or DeleteManyModel.

Tip

By default, MongoDB executes operations in a bulk write in the specified order. During an ordered bulk write, if an error occurs during the processing of an operation, MongoDB returns without processing the remaining operations in the list.

In contrast, when you set the ordered option to false, MongoDB continues to process the remaining write operations in the list even in the event of an error. Unordered operations are usually faster since MongoDB can execute them in parallel, but only use an unordered bulk write if the order of your write operations is not important.

The bulkWrite() method returns a BulkWriteResult object that contains information about the write operation results including the number of documents inserted, modified, and deleted.

If one or more of your operations attempts to set a value that violates a unique index on your collection, an exception is raised that should look something like this:

The bulk write operation failed due to an error: Bulk write operation error on server <hostname>. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: ... }].

Similarly, if you attempt to perform a bulk write against a collection that uses schema validation and one or more of your write operations provide an unexpected format, you might encounter exceptions.

The following code sample performs an ordered bulk write operation on the movies collection in the sample_mflix database. The example call to bulkWrite() includes examples of the InsertOneModel, UpdateOneModel, and DeleteOneModel.

Note

This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

// Runs bulk write operations on a collection by using the Java driver
package usage.examples;
import java.util.Arrays;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.DeleteOneModel;
import com.mongodb.client.model.InsertOneModel;
import com.mongodb.client.model.ReplaceOneModel;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.UpdateOptions;
public class BulkWrite {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
try {
// Runs a bulk write operation for the specified insert, update, delete, and replace operations
BulkWriteResult result = collection.bulkWrite(
Arrays.asList(
new InsertOneModel<>(new Document("name", "A Sample Movie")),
new InsertOneModel<>(new Document("name", "Another Sample Movie")),
new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")),
new UpdateOneModel<>(new Document("name", "A Sample Movie"),
new Document("$set", new Document("name", "An Old Sample Movie")),
new UpdateOptions().upsert(true)),
new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")),
new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"),
new Document("name", "The Other Sample Movie").append("runtime", "42"))
));
// Prints the number of inserted, updated, and deleted documents
System.out.println("Result statistics:" +
"\ninserted: " + result.getInsertedCount() +
"\nupdated: " + result.getModifiedCount() +
"\ndeleted: " + result.getDeletedCount());
// Prints a message if any exceptions occur during the operations
} catch (MongoException me) {
System.err.println("The bulk write operation failed due to an error: " + me);
}
}
}
}

The output of the preceding code resembles the following:

Result statistics:
inserted: 3
updated: 2
deleted: 1

Tip

Legacy API

If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.

For additional information on the classes and methods mentioned on this page, see the following resources:

  • Unique Index Server Manual Entry

  • Schema Validation Server Manual Entry

  • bulkWrite() API Documentation

  • BulkWriteOptions API Documentation

  • BulkWriteResult API Documentation

  • InsertOneModel API Documentation

  • UpdateOneModel API Documentation

  • UpdateManyModel API Documentation

  • DeleteOneModel API Documentation

  • DeleteManyModel API Documentation

  • ReplaceOneModel API Documentation

←  Delete Multiple DocumentsWatch for Changes →