Overview
In this guide, you can learn how to use the Kotlin driver to replace documents in a MongoDB collection. A replace operation uses a query filter to match a document in a collection, then replaces the document with a new one.
Replace One Document
The replaceOne()
method removes all the existing fields and values in the
matching document (except the _id field) and inserts the fields and values from the
replacement document.
You can call the replaceOne() method on a MongoCollection
instance as follows:
collection.replaceOne(<query>, <replacementDocument>)
If multiple documents match the query filter specified in
the replaceOne() method, the operation replaces the first result. You can
specify a sort in a ReplaceOptions instance to apply an order to
matched documents before the driver performs the replace operation, as
shown in the following code:
val opts = ReplaceOptions().sort(Sorts.ascending(PaintOrder::color.name))
If zero documents match the query filter in the replace operation,
replaceOne() makes no changes to documents in the collection. See
the Upsert guide to
learn how to insert a new document instead of replacing one if no
documents match.
Important
The replaceOne() method cannot make changes to a document that
violates unique index constraints on the collection. See the MongoDB
Server manual for more information about unique indexes.
Replace Operation Parameters
The replaceOne() method accepts the following parameters:
Parameter | Description |
|---|---|
| A query filter that specifies the document to replace. For more information about query filters, see the MongoDB Server manual. Data Type: BSON |
| A replacement document, which specifies the fields and values to insert in the new document. If the documents in your collection are mapped to a Kotlin class, the replacement document can be an instance of this class. Data Type: |
| Optional. An instance of the Data Type: ReplaceOptions |
Customize the Replace Operation
The replaceOne() method optionally accepts a ReplaceOptions object as a parameter,
which represents options you can use to configure the replace operation.
The ReplaceOptions class contains the following properties:
Property | Description |
|---|---|
| Specifies whether the replace operation bypasses document validation. This lets you replace documents that don't meet the schema validation requirements, if any exist. See the MongoDB Server manual for more information on schema validation. Data Type: boolean |
| Specifies the kind of language collation to use when sorting results. Data Type: Collation |
| Gets or sets the user-provided comment for the operation. See the MongoDB Server manual for more information. |
| Gets or sets the index to use to scan for documents. See the MongoDB Server manual for more information. Data Type: Bson |
| Gets or sets the index to use to scan for documents. See the MongoDB Server manual for more information. Data Type: String |
| Specifies whether the replace operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information. Data Type: boolean |
| Determines which document the operation replaces if the query selects multiple documents, because the replace operation replaces the first document in the sort order specified. Data Type: Bson |
| Gets or sets the let document to add top-level variables for the operation. See the MongoDB Server manual for more information. Data Type: Bson |
Return Value
Upon successful execution, the replaceOne() method returns an UpdateResult
instance. The UpdateResult class contains the following properties:
Property | Description |
|---|---|
| Indicates whether the replace operation was acknowledged by MongoDB. Data Type: |
| The number of documents that matched the query filter, regardless of whether one was replaced. Data Type: |
| The number of documents replaced by the replace operation. Data Type: |
| The ID of the document that was upserted in the database, if the driver performed an upsert. Data Type: BsonValue |
Exceptions
If your replacement operation fails, the driver raises an exception.
For example, if the value of the _id field in your replacement document differs from
the value in the original document, the method throws the following
MongoWriteException:
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 similar to the following:
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.
Replace One Example
A paint store sells five different colors of paint. The documents in the following collection represent paint colors in the store's inventory:
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 3, "color": "yellow", "qty": 0 } { "_id": 4, "color": "green", "qty": 6 } { "_id": 5, "color": "pink", "qty": 20 }
The following Kotlin data class models this data:
data class PaintOrder( val id: Int, val color: String, val qty: Int )
The paint store must update their inventory to replace 20 cans of pink paint with 25 cans of orange paint.
To update the inventory, call the replaceOne() method:
val filter = Filters.eq(PaintOrder::color.name, "pink") val update = PaintOrder(5, "orange", 25) val result = collection.replaceOne(filter, update) println("Matched document count: $result.matchedCount") println("Modified document count: $result.modifiedCount")
Matched document count: 1 Modified document count: 1
The preceding replace operation creates the following document:
{ "_id": 5, "color": "orange", "qty": 25 }
Advanced Replace One Example
In the following example, the replaceOne() method replaces the first match of the
query filter in the movies collection of the Atlas sample_mflix.movies dataset with a replacement document. The operation deletes
all fields except _id from the original document and inserts the fields from the
replacement document. The following Movie data class models the documents in this
collection for use with the Kotlin driver:
data class Movie( val title: String, val year: Int, val genres: List<String>, val rated: String, val plot: String, val runtime: Int, val imdb: IMDB, val fullplot: String? = "No full plot", ){ data class IMDB( val rating: Double ) }
Tip
Builder Methods and Data Class Properties
You can use the methods from builder classes directly with data class properties by adding the optional Kotlin driver extensions dependency to your application. To learn more and view examples, see the Use Builders with Data Classes guide.
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 example uses the following objects and methods:
A query filter that is passed to the
replaceOne()method. Theeqfilter 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
upsertoption set totrue. This option specifies that the method inserts the data contained in the replacement document if the query filter does not match any documents.
Note
This example connects to an instance of MongoDB by 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") } mongoClient.close() }
The preceding example returns the following output:
Modified document count: 1 Upserted id: null
If the preceding example resulted in an upsert, the code returns the following output:
Modified document count: 0 Upserted id: BsonObjectId{value=...}
If you query the replaced document, the query returns the following output:
Movie(title=50 Violins, fullplot= A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music)
Additional Information
To learn more about the methods and classes used on this page, see the following API documentation: