Skip to content

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

upsertOne

abstract suspend fun upsertOne(options: ERROR CLASS: Symbol not found for UpdateOptions.() -> Unit = {}, filter: ERROR CLASS: Symbol not found for FilterQuery.() -> Unit = {}, update: ERROR CLASS: Symbol not found for UpsertQuery.() -> Unit)

Updates a single document that matches filter according to update.

If multiple documents match filter, only the first one is updated.

If no documents match filter, a new one is created.

Example

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

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

If a document exists that has the name of "Patrick", its age is set to 15. If none exists, a document with name "Patrick" and age 15 is created.

Using filtered collections

The following code is equivalent:

collection.filter {
    User::name eq "Patrick"
}.upsertOne {
    User::age set 15
}

To learn more, see filter.

External resources

See also