repsertOne

open suspend override fun repsertOne(options: ReplaceOptions<Document>.() -> Unit, filter: FilterQuery<Document>.() -> Unit, document: Document)(source)

Replaces a document that matches filter by document.

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

If no documents match filter, document is InsertOperations.insertOne.

Data races

This operator is often used by first reading a document, processing it, and replacing it. This can be dangerous in distributed systems because another replica of the server could have updated the document between the read and the write.

If this is a concern, it is recommended to use updateOne with explicit operators on the data that has changed, allowing to do the modification in a single operation. Doing the update that way, MongoDB is responsible for ensuring the read and the write are atomic.

Example

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

collection.repsertOne(
filter = {
User::name eq "Patrick"
},
document = User("Bob", 15)
)

Using filtered collections

The following code is equivalent:

collection.filter {
User::name eq "Patrick"
}.repsertOne(User("Patrick", 15))

To learn more, see filter.

External resources

Parameters

filter

Optional filter to select which document is updated. If no filter is specified, the first document found is updated.

See also

Updates an existing document.

Replaces an existing document.

Also returns the result of the update.