Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava

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():

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

The bulkWrite() method accepts the following parameters:

  • A List of objects that implement WriteModel: the classes that implement WriteModel correspond to the aforementioned write operations. E.g. the InsertOneModel class wraps the insertOne write operation. See the links to the API documentation at the bottom of this page for more information on 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 bulk write operations one-by-one in the specified order (i.e. serially). 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 ordered to false, MongoDB continues to process remaining write operations in the list in the event of an error. Unordered operations are theoretically faster since MongoDB can execute them in parallel, but you should only use them if your writes do not depend on order.

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 may 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.

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 {
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"))
));
System.out.println("Result statistics:" +
"\ninserted: " + result.getInsertedCount() +
"\nupdated: " + result.getModifiedCount() +
"\ndeleted: " + result.getDeletedCount());
} catch (MongoException me) {
System.err.println("The bulk write operation failed due to an error: " + me);
}
}
}
}

The output should look something like this:

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:

←  Delete Multiple DocumentsWatch for Changes →