Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversKotlin Coroutine

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. For example, 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.

import com.mongodb.MongoException
import com.mongodb.client.model.DeleteOneModel
import com.mongodb.client.model.Filters
import com.mongodb.client.model.InsertOneModel
import com.mongodb.client.model.ReplaceOneModel
import com.mongodb.client.model.UpdateOneModel
import com.mongodb.client.model.UpdateOptions
import com.mongodb.client.model.Updates
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
data class Movie(val title: String, val runtime: Int? = null)
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
try {
val result = collection.bulkWrite(
listOf(
InsertOneModel(Movie("A Sample Movie")),
InsertOneModel(Movie("Another Sample Movie")),
InsertOneModel(Movie("Yet Another Sample Movie")),
UpdateOneModel(
Filters.eq(Movie::title.name,"A Sample Movie"),
Updates.set(Movie::title.name, "An Old Sample Movie"),
UpdateOptions().upsert(true)
),
DeleteOneModel(Filters.eq("title", "Another Sample Movie")),
ReplaceOneModel(
Filters.eq(Movie::title.name, "Yet Another Sample Movie"),
Movie("The Other Sample Movie", 42)
)
)
)
println(
"""
Result statistics:
inserted: ${result.insertedCount}
updated: ${result.modifiedCount}
deleted: ${result.deletedCount}
""".trimIndent()
)
} catch (e: MongoException) {
System.err.println("The bulk write operation failed due to an error: $e")
}
mongoClient.close()
}

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 →