Skip to content

MongoDB driver for Kotlin (coroutines)opensavvy.ktmongo.coroutines.operationsUpdateOperationsbulkWrite

bulkWrite

abstract suspend fun bulkWrite(options: <Document>.() -> Unit = {}, filter: <Document>.() -> Unit = {}, operations: <Document>.() -> Unit)

Performs multiple update operations in a single request.

Example

class User(
    val name: String,
    val age: Int,
)

collection.bulkWrite {
    upsertOne(
        filter = {
            User::name eq "Patrick"
        },
        update = {
            User::age set 15
        }
    )

    updateMany {
        User::age inc 1
    }
}

To see which operations are available and their respective syntax, see BulkWrite.

Using filtered writes

We can group operations by the filter they apply on:

collection.bulkWrite {
    filtered(filter = { User::isAlive eq true }) {
        updateOne()
        updateOne()
        updateMany()
    }

    updateOne()
}

To learn more, see BulkWrite.filtered.

Using filtered collections

If we want all operations to use the same filter, we can declare it before calling the operation:

collection.filter {
    User::isAlive eq true
}.bulkWrite {
    updateOne()
    updateOne()
    updateMany()
}

External resources