MongoDB driver for Kotlin (coroutines) • opensavvy.ktmongo.coroutines • JvmMongoCollection • replaceOne
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:
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¶
-
JvmMongoCollection.updateOneUpdates an existing document. -
JvmMongoCollection.updateManyUpdate more than one document. -
JvmMongoCollection.repsertOneReplaces a document, or inserts it if it doesn't exist. -
JvmMongoCollection.findOneAndUpdateAlso returns the result of the update.