Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ / /

Modify Documents

On this page

  • Overview
  • Update
  • Update Operation Parameters
  • Update One Example
  • Update Many Example
  • Replace
  • Replace Operation Parameters
  • Replace One Example

In this guide, you can learn how to modify documents in a MongoDB collection using two distinct operation types:

  • Update

  • Replace

Update operations specify the fields and values to change in one or more documents. A replace operation specifies the fields and values to replace a single document from your collection.

In the following examples, a paint store sells five different colors of paint. The paint_inventory collection represents their current 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": 0 }

This data is modeled with the following Kotlin data class:

data class PaintOrder(
@BsonId val id: Int,
val color: String,
val qty: Int
)

Update operations can modify fields and values. They apply changes specified in an update document to one or more documents that match your query filter.

The updateOne() method changes the first document your query filter matches and the updateMany() method changes all the documents your query filter matches.

You can call the updateOne() and updateMany() methods on a MongoCollection instance as follows:

collection.updateOne(<query>, <updateDocument>)
collection.updateMany(<query>, <updateDocument>)

The updateOne() and updateMany() methods both have the following parameters:

  • query specifies a query filter with the criteria to match documents to update in your collection

  • updateDocument specifies the fields and values to modify in the matching document or documents. This example uses the Updates builder methods to create the update document.

  • (Optional) updateOptions specifies options that you can set to customize how the driver performs the update operation. To learn more about this type, see the API documentation for UpdateOptions.

You can create the updateDocument using an Updates builder as follows:

val updateDocument = Updates.operator(<field>, <value>)

To view a complete list of Updates builders and their usage, see Updates in the API documentation.

The paint store needs to update their inventory after a customer returns a can of yellow paint.

To update the single can of paint, call the updateOne() method specifying the following:

  • Query filter that matches the yellow color

  • Update document that contains instructions to increment the qty field by 1

val filter = Filters.eq(PaintOrder::color.name, "yellow")
val update = Updates.inc(PaintOrder::qty.name, 1)
val result = collection.updateOne(filter, update)
println("Matched document count: $result.matchedCount")
println("Modified document count: $result.modifiedCount")
Matched document count: 1
Modified document count: 1

If multiple documents match the query filter specified in the updateOne() method, it updates the first result. You can specify a sort in an UpdateOptions instance to apply an order to matched documents before the driver performs the update operation, as shown in the following code:

val opts = UpdateOptions().sort(Sorts.ascending(PaintOrder::color.name))

The paint store then receives a fresh shipment and needs to update their inventory again. The shipment contains 20 cans of each paint color.

To update the inventory, call the updateMany() method specifying the following:

  • Query filter that matches all the colors

  • Update document that contains instructions to increment the qty field by 20

val filter = Filters.empty()
val update = Updates.inc(PaintOrder::qty.name, 20)
val result = collection.updateMany(filter, update)
println("Matched document count: $result.matchedCount")
println("Modified document count: $result.modifiedCount")
Matched document count: 5
Modified document count: 5

The following shows the updated documents in the paint_inventory collection:

{ "_id": 1, "color": "red", "qty": 25 }
{ "_id": 2, "color": "purple", "qty": 28 }
{ "_id": 3, "color": "yellow", "qty": 20 }
{ "_id": 4, "color": "green", "qty": 26 }
{ "_id": 5, "color": "pink", "qty": 20 }

If zero documents match the query filter in the update operation, updateMany() makes no changes to documents in the collection. See the Upsert guide to learn how to insert a new document instead of updating one if no documents match.

Important

The updateOne() and updateMany() methods cannot make changes to a document that violate unique index constraints on the collection. See the MongoDB server manual for more information on unique indexes.

A replace operation substitutes one document from your collection. The substitution occurs between a document your query filter matches and a replacement document.

The replaceOne() method removes all the existing fields and values in the matching document (except the _id field) and substitutes it with the replacement document.

You can call the replaceOne() method on a MongoCollection instance as follows:

collection.replaceOne(<query>, <replacementDocument>)

The replaceOne() method has the following parameters:

  • query specifies a query filter with the criteria to match a document to replace in your collection

  • replacementDocument specifies fields and values of a new Document object to replace in the matched document

  • (Optional) replaceOptions specifies options that you can set to customize how the driver performs the replace operation. To learn more about this type, see the API documentation for ReplaceOptions.

The paint store realizes they need to update their inventory again. What they thought was 20 cans of pink paint is actually 25 cans of orange paint.

To update the inventory, call the replaceOne() method specifying the following:

  • Query filter that matches documents where the color is "pink"

  • Replacement document where the color is "orange" and the qty is "25"

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 following shows the updated document:

{ "_id": 5, "color": "orange", "qty": 25 }

If multiple documents match the query filter specified in the replaceOne() method, it 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 violate unique index constraints on the collection. See the MongoDB server manual for more information on unique indexes.

Back

Delete Documents