Docs 菜单

替换文档

在本指南中,您可以学习;了解如何使用Scala驾驶员对MongoDB集合中的文档执行替换操作。替换操作会删除指定文档中除 _id字段之外的所有字段和值,并添加您指定的新字段和值。 此操作与更新操作不同,更新操作仅更改一个或多个文档中的指定字段。

要学习;了解有关更新操作的更多信息,请参阅更新文档指南。

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

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

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

您可以使用 replaceOne() 方法在MongoDB中执行替换操作。 此方法会从与指定查询过滤匹配的第一个文档中删除除 _id字段之外的所有字段。 然后,它将您指定的字段和值添加到空文档中。

您必须将以下参数传递给replaceOne()方法:

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

  • 替换文档,指定要替换现有字段和值的字段和值。

以下示例使用 replaceOne() 方法替换 name字段值为 "Primola Restaurant" 的文档的字段和值:

val filter = equal("name", "Primola Restaurant")
val replacement = Document(
"name" -> "Frutti Di Mare",
"borough" -> "Queens",
"cuisine" -> "Seafood",
"owner" -> "Sal Thomas"
)
val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}")
override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}")
override def onComplete(): Unit = println("Completed")
})
Replaced document count: 1
Completed

重要

_id字段的值不可变。 如果替换文档为 _id字段指定了值,则该值必须与现有文档的 _id 值相同,否则驾驶员将引发 WriteError

replaceOne() 方法可以选择接受 ReplaceOptions数据类型的参数。 ReplaceOptions 类包含可用于配置替换选项的 setter 方法。 如果不指定任何选项,驾驶员将使用默认设置执行替换操作。

下表描述了 ReplaceOptions 类中的 setter 方法:

方法
说明

upsert()

Specifies whether the replace operation performs an upsert operation if no documents match the query filter. For more information, see upsert behavior 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 replaceOne() method, the operation replaces the first result. You can set this option to apply an order to matched documents to have more control over which document is replaced.

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.

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.

comment()

Sets a comment to attach to the operation.

以下代码将upsert选项设置为true ,这会指示驾驶员在查询过滤与任何现有文档都不匹配时插入具有替换文档中指定的字段和值的新文档:

val options = ReplaceOptions().upsert(true)
val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement, options)
observable.subscribe(new Observer[UpdateResult] {
override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}")
override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}")
override def onComplete(): Unit = println("Completed")
})
Replaced document count: 1
Completed

replaceOne()方法返回一个UpdateResult对象。 您可以使用以下方法访问权限UpdateResult实例中的信息:

方法
说明

getMatchedCount()

Returns the number of documents that matched the query filter.

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 the driver upserted into the database, if any.

要查看演示如何替换文档的可运行代码示例,请参阅将数据写入MongoDB。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档: