Docs 菜单
Docs 主页
/ / /
Scala 驱动程序
/

Update Documents

在此页面上

  • Overview
  • 样本数据
  • 更新操作
  • 更新一个文档示例
  • 更新多个文档示例
  • 自定义更新操作
  • 返回值
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用Scala驾驶员通过 updateOne()updateMany() 方法更新MongoDB集合中的文档。

本指南中的示例使用restaurants sample_restaurantsAtlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到Atlas 集群的MongoClient,然后为 databasecollection 变量分配以下值:

val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

您可以使用以下方法更新MongoDB中的文档:

  • updateOne(),更新匹配搜索条件的第一个文档

  • updateMany(),更新与搜索条件匹配的所有文档

每种更新方法都需要以下参数:

  • 查询过滤,用于匹配要更新的文档。要学习;了解有关查询筛选器的更多信息,请参阅《 指定查询》指南。

  • 更新文档,指定更新操作符以及要更新的字段和值。更新操作符指定要执行的更新类型。 要查看更新操作符列表并学习;了解其用法,请参阅MongoDB Server手册中的字段更新操作符指南页面。

以下示例使用 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 方法:

方法
说明

upsert()

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

sort()

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.

bypassDocumentValidation()

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.

collation()

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

arrayFilters()

Provides a list of filters that you specify to select which array elements the update applies to.

hint()

Sets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.

let()

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.

comment()

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实例中的信息:

方法
说明

getMatchedCount()

Returns the number of documents that matched the query filter, regardless of how many updates were performed.

getModifiedCount()

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.

wasAcknowledged()

Returns true if the server acknowledged the result.

getUpsertedId()

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 文档:

后退

替换