Update Documents
Overview
在本指南中,您可以学习;了解如何使用Scala驾驶员通过 updateOne()
和 updateMany()
方法更新MongoDB集合中的文档。
样本数据
本指南中的示例使用restaurants
sample_restaurants
Atlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到Atlas 集群的MongoClient
,然后为 database
和 collection
变量分配以下值:
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。
更新操作
您可以使用以下方法更新MongoDB中的文档:
updateOne()
,更新匹配搜索条件的第一个文档updateMany()
,更新与搜索条件匹配的所有文档
每种更新方法都需要以下参数:
更新一个文档示例
以下示例使用 updateOne()
方法将文档的 name
字段值从 "Happy Garden"
更新为 "Mountain
House"
。 更新文档使用 set()
方法更新name
字段值:
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
更新多个文档示例
以下示例使用 updateMany()
方法更新name
字段值为 "Starbucks"
的所有文档。 更新文档使用 rename()
方法将 address
字段的名称更改为 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
自定义更新操作
updateOne()
和updateMany()
方法可以选择接受一个参数,该参数设置配置更新操作的选项。 如果不指定任何选项,驾驶员将使用默认设置执行更新操作。
下表描述了可用于配置UpdateOptions
实例的 setter 方法:
方法 | 说明 |
---|---|
| 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. |
修改更新示例
此示例创建选项并将其传递给 updateOne()
方法。 该示例使用 equal()
辅助方法来匹配 name
字段值为 "Sunrise Pizzeria"
的文档。 然后,它使用 set()
方法将第一个匹配文档中的 borough
字段值设立为 "Queens"
,并将 cuisine
字段值设置为 "Italian"
。 该代码使用 combine()
方法在一个更新文档中指定多个更新。
由于 upsert
选项在 UpdateOptions
实例中设立为 true
,因此,如果查询过滤与任何现有文档都不匹配,则驾驶员会插入包含过滤和更新文档中指定的字段和值的新文档。
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
返回值
updateOne()
和updateMany()
方法各自返回一个UpdateResult
对象。 您可以使用以下方法访问权限UpdateResult
实例中的信息:
方法 | 说明 |
---|---|
| 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. |
注意
如果wasAcknowledged()
方法返回false
,则尝试从UpdateResult
实例访问权限其他信息会导致InvalidOperation
异常。 如果服务器未确认写入操作,则驾驶员无法确定这些值。
更多信息
要查看演示如何使用Scala驾驶员更新文档的可运行代码示例,请参阅将数据写入MongoDB。
API 文档
要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: