Update Documents
On this page
Overview
In this guide, you can learn how to use the Scala driver to update
documents in a MongoDB collection by using the updateOne()
and
updateMany()
methods.
Sample Data
The examples in this guide use the restaurants
collection in the sample_restaurants
database from the Atlas sample datasets. To access this collection
from your Scala application, create a MongoClient
that connects to an Atlas cluster
and assign the following values to your database
and collection
variables:
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.
Update Operations
You can update documents in MongoDB by using the following methods:
updateOne()
, which updates the first document that matches the search criteriaupdateMany()
, which updates all documents that match the search criteria
Each update method requires the following parameters:
Query filter, which matches the documents you want to update. To learn more about query filters, see the Specify a Query guide.
Update document, which specifies the update operator and the fields and values to be updated. The update operator specifies the type of update to perform. To view a list of update operators and learn about their usages, see the Field Update Operators guide page in the MongoDB Server manual.
Update One Document Example
The following example uses the updateOne()
method to update the
name
field value of a document from "Happy Garden"
to "Mountain
House"
. The update document uses the set()
method to update the name
field
value:
val filter = equal("name", "Happy Garden") val update = set("name", "Mountain House") val observable: Observable[UpdateResult] = collection.updateOne(filter, update) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 1 Completed
Update Many Documents Example
The following example uses the updateMany()
method to update all documents
in which the name
field value is "Starbucks"
. The update document uses the
rename()
method to change the name of the address
field to location
:
val filter = equal("name", "Starbucks") val update = rename("address", "location") val observable: Observable[UpdateResult] = collection.updateMany(filter, update) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 11 Completed
Customize the Update Operation
The updateOne()
and updateMany()
methods optionally accept
a parameter that sets options to configure the update operation.
If you don't specify any options, the driver performs update
operations with default settings.
The following table describes the setter methods that you can use to
configure an UpdateOptions
instance:
Method | Description |
---|---|
| Specifies whether the update operation performs an upsert operation if no
documents match the query filter. For more information, see the upsert
statement
in the MongoDB Server manual. Defaults to false |
| Sets the sort criteria to apply to the operation. If multiple
documents match the query filter that you pass to the
updateOne() method, the operation updates the first
result. You can set this option to apply an order to matched
documents to have more control over which document is updated. |
| Specifies whether the update operation bypasses document validation. This lets you
update documents that don't meet the schema validation requirements, if any
exist. For more information about schema validation, see Schema
Validation in the MongoDB
Server manual. Defaults to false . |
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Provides a list of filters that you specify to select which
array elements the update applies to. |
| Sets the index to use when matching documents.
For more information, see the hint statement
in the MongoDB Server manual. |
| Provides a map of parameter names and values to set top-level
variables for the operation. Values must be constant or closed
expressions that don't reference document fields. For more information,
see the let statement in the
MongoDB Server manual. |
| Sets a comment to attach to the operation. For more
information, see the update command
fields guide in the
MongoDB Server manual for more information. |
Modify Update Example
This example creates and passes options to the updateOne()
method.
The example uses the equal()
helper method to match documents
in which the name
field value is "Sunrise Pizzeria"
. It then uses the set()
method to set the borough
field value in the first matching document to
"Queens"
and the cuisine
field value to "Italian"
. The code uses the
combine()
method to specify multiple updates in one update document.
Because the upsert
option is set to true
in the UpdateOptions
instance,
the driver inserts a new document that has the fields and values specified in the filter
and update document if the query filter doesn't match any existing documents.
val filter = equal("name", "Sunrise Pizzeria") val opts = UpdateOptions().upsert(true) val update = combine( set("borough", "Queens"), set("cuisine", "Italian") ) val observable: Observable[UpdateResult] = collection.updateOne(filter, update, opts) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 1 Completed
Return Value
The updateOne()
and updateMany()
methods each return an UpdateResult
object. You can use the following methods to access information from
an UpdateResult
instance:
Method | Description |
---|---|
| Returns the number of documents that matched the query filter, regardless of
how many updates were performed. |
| Returns the number of documents modified by the update operation. If an updated
document is identical to the original, it is not included in this
count. |
| Returns true if the server acknowledged the result. |
| Returns the _id value of the document that was upserted
in the database, if the driver performed an upsert. |
Note
If the wasAcknowledged()
method returns false
, trying to
access other information from the UpdateResult
instance results in an
InvalidOperation
exception. The driver cannot
determine these values if the server does not acknowledge the write
operation.
Additional Information
To view runnable code examples that demonstrate how to update documents by using the Scala driver, see Write Data to MongoDB.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: