Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversKotlin Coroutine

Replace a Document

You can replace a single document using the replaceOne() method on a MongoCollection object. This method removes all the existing fields and values from a document (except the _id field) and substitutes it with your replacement document.

The replaceOne() method accepts a query filter that matches the document you want to replace and a replacement document that contains the data you want to save in place of the matched document. The replaceOne() method only replaces the first document that matches the filter.

You can optionally pass an instance of ReplaceOptions to the replaceOne() method in order to specify the method's behavior. For example, if you set the upsert field of the ReplaceOptions object to true, the operation inserts a new document from the fields in the replacement document if no documents match the query filter. See the link to the ReplaceOptions API documentation at the bottom of this page for more information.

Upon successful execution, the replaceOne() method returns an instance of UpdateResult. You can retrieve information such as the number of documents modified by calling the getModifiedCount() method. You can also retrieve the value of the document's _id field by calling the getUpsertedId() method if you set upsert(true) in the ReplaceOptions instance and the operation resulted in the insertion of a new document.

If your replacement operation fails, the driver raises an exception. For example, if you try to specify a value for the immutable field _id in your replacement document that differs from the original document, the method throws a MongoWriteException with the message:

After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...)

If your replacement document contains a change that violates unique index rules, the method throws a MongoWriteException with an error message that should look something like this:

E11000 duplicate key error collection: ...

For more information on the types of exceptions raised under specific conditions, see the API documentation for replaceOne(), linked at the bottom of this page.

In this example, we replace the first match of our query filter in the movies collection of the sample_mflix database with a replacement document. All the fields except for the _id field are deleted from the original document and are substituted by the replacement document.

Before the replaceOne() operation runs, the original document contains several fields describing the movie. After the operation runs, the resulting document contains only the fields specified by the replacement document (title and fullplot) and the _id field.

The following snippet uses the following objects and methods:

  • A query filter that is passed to the replaceOne() method. The eq filter matches only movies with the title exactly matching the text 'Music of the Heart'.

  • A replacement document that contains the document that replaces the matching document if it exists.

  • A ReplaceOptions object with the upsert option set to true. This option specifies that the method should insert the data contained in the replacement document if the query filter does not match any documents.


This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.

import com.mongodb.MongoException
import com.mongodb.client.model.Filters
import com.mongodb.client.model.ReplaceOptions
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
data class Movie(val title: String, val fullplot: String)
fun main() = runBlocking {
// Replace the uri string with your MongoDB deployment's connection string
val uri = "<connection string uri>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
try {
val query = Filters.eq("title", "Music of the Heart")
val replaceDocument = Movie( "50 Violins", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music")
val options = ReplaceOptions().upsert(true)
val result = collection.replaceOne(query, replaceDocument, options)
println("Modified document count: " + result.modifiedCount)
println("Upserted id: " + result.upsertedId) // only contains a non-null value when an upsert is performed
} catch (e: MongoException) {
System.err.println("Unable to replace due to an error: $e")

After you run the example, you should see output that looks something like this:

Modified document count: 1
Upserted id: null

Or if the example resulted in an upsert:

Modified document count: 0
Upserted id: BsonObjectId{value=...}

If you query the replaced document, it should look something like this:

Movie(title=50 Violins, fullplot= A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music)

For additional information on the classes and methods mentioned on this page, see the following API Documentation:

  • ReplaceOne

  • ReplaceOptions

  • UpdateResult

  • eq()

←  Update Multiple DocumentsDelete Operations →