替换文档
您可以使用 replaceOne() 方法在 MongoCollection 对象上替换单个文档。此方法移除文档中除 _id 字段之外的所有字段和值,并用您的替换文档替换它。
replaceOne() 方法接受一个查询过滤器,用于匹配要替换的文档,以及一个包含您想要保存的数据的替换文档,以替换匹配的文档。该方法仅替换与过滤器匹配的第一个文档。
您可以可选地传递一个 ReplaceOptions 实例给 replaceOne() 方法来指定该方法的行为。例如,如果您将 ReplaceOptions 对象的 upsert 字段设置为 true,则在没有文档与查询过滤器匹配时,操作将插入一个包含替换文档字段的新文档。有关更多信息,请参阅本页底部的 ReplaceOptions API 文档链接。
执行成功后,replaceOne() 方法返回一个 UpdateResult 实例。您可以通过调用 getModifiedCount() 方法来检索修改的文档数量。如果您在 ReplaceOptions 实例中设置了 upsert(true),并且操作导致插入新文档,您还可以通过调用 getUpsertedId() 方法来检索文档的 _id 字段的值。
如果您的替换操作失败,驱动程序将抛出一个异常。例如,如果您尝试在替换文档中指定与原始文档不同的不可变字段 _id 的值,则方法将抛出包含以下消息的 MongoWriteException。
After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...) 
如果您的替换文档包含违反唯一索引规则的更改,则方法将抛出包含类似以下错误消息的 MongoWriteException。
E11000 duplicate key error collection: ... 
有关特定条件下引发的异常类型的信息,请参阅本页底部链接的 replaceOne() API 文档。
示例
在这个示例中,我们用替换文档替换了 sample_mflix 数据库中 movies 集合中查询过滤器匹配的第一个文档。除了 _id 字段外,原始文档的所有字段都被删除,并替换为替换文档。
在 replaceOne() 操作之前,原始文档包含描述电影的几个字段。在操作之后,结果文档只包含替换文档指定的字段(title 和 fullplot)以及 _id 字段。
以下代码片段使用了以下对象和方法
- 传递给 - replaceOne()方法的 查询过滤器。该- eq过滤器仅匹配标题与文本- 'Music of the Heart'完全匹配的电影。
- 包含替换匹配文档的文档的 替换文档。 
- 一个带有 - upsert选项设置为- true的 ReplaceOptions 对象。此选项指定如果查询过滤器不匹配任何文档,则应插入替换文档中包含的数据。
注意
此示例使用连接 URI 连接到 MongoDB 实例。要了解有关连接到您的 MongoDB 实例的更多信息,请参阅连接指南.
import com.mongodb.MongoException import com.mongodb.client.model.Filters import com.mongodb.client.model.ReplaceOptions import com.mongodb.kotlin.client.coroutine.MongoClient import kotlinx.coroutines.runBlocking data class Movie(val title: String, val fullplot: String) fun main() = runBlocking {     // Replace the uri string with your MongoDB deployment's connection string     val uri = "<connection string uri>"     val mongoClient = MongoClient.create(uri)     val database = mongoClient.getDatabase("sample_mflix")     val collection = database.getCollection<Movie>("movies")     try {         val query = Filters.eq("title", "Music of the Heart")         val replaceDocument = Movie( "50 Violins", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music")         val options = ReplaceOptions().upsert(true)         val result = collection.replaceOne(query, replaceDocument, options)         println("Modified document count: " + result.modifiedCount)         println("Upserted id: " + result.upsertedId) // only contains a non-null value when an upsert is performed     } catch (e: MongoException) {         System.err.println("Unable to replace due to an error: $e")     }     mongoClient.close() } 
运行示例后,您应该看到类似以下输出的内容
Modified document count: 1 Upserted id: null 
或者如果示例导致 upsert
Modified document count: 0 Upserted id: BsonObjectId{value=...} 
如果您查询被替换的文档,它应该看起来像这样
Movie(title=50 Violins, fullplot= A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music) 
有关此页面上提到的类和方法的更多信息,请参阅以下 API 文档