replaceOne
Replaces a document that matches filter by document.
If multiple documents match filter, only the first one found is updated.
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.replaceOne(
filter = {
User::name eq "Patrick"
},
document = User("Bob", 15)
)
Using filtered collections
The following code is equivalent:
collection.filter {
User::name eq "Patrick"
}.replaceOne(User("Patrick", 15))
To learn more, see filter.
External resources
Parameters
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.
Update more than one document.
Replaces a document, or inserts it if it doesn't exist.
Also returns the result of the update.