Docs 菜单
Docs 主页
/ / /
Kotlin 协程
/ /

替换文档

您可以在MongoCollection对象上使用 replaceOne()方法来替换单个文档。 此方法会删除文档中的所有现有字段和值( _id字段除外),并将其替换为替换文档。

replaceOne()方法接受与要替换的文档匹配的查询筛选器,以及包含要保存以代替匹配文档的数据的替换文档。 replaceOne()方法仅替换与过滤器匹配的第一个文档。

您可以选择将ReplaceOptions的实例传递给replaceOne()方法,以指定该方法的行为。 例如,如果将ReplaceOptions对象的upsert字段设置为true ,则如果没有文档与查询筛选器匹配,操作则会插入替换文档中字段的新文档。 有关更多信息,请参阅本页底部的ReplaceOptions API 文档链接。

成功执行后, replaceOne()方法将返回UpdateResult的实例。 您可以通过调用getModifiedCount()方法来检索已修改文档数量等信息。 如果您在实例中设置了_id getUpsertedId()upsert(true)ReplaceOptions,并且操作导致插入了新文档,则还可以通过调用 方法检索文档的字段的值。

如果替换操作失败,驱动程序会引发异常。 例如,如果您尝试在替换文档中为不可变字段_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()操作运行之前,原始文档包含多个描述电影的字段。操作运行后,生成的文档仅包含替换文档指定的字段( titlefullplot )以及_id字段。

以下代码段使用以下对象和方法:

  • 传递给 replaceOne() 方法的查询筛选器eq 筛选器仅会匹配标题与 'Music of the Heart' 文本完全匹配的电影。

  • 替换文档,其中包含用于替换匹配文档(如果存在)的文档。

  • upsert选项设置为trueReplaceOptions对象。 此选项指定,如果查询筛选器与任何文档都不匹配,则该方法应插入替换文档中包含的数据。

注意

此示例使用连接 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

或者,如果示例导致更新或插入:

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

  • replaceOne

  • ReplaceOptions

  • UpdateResult

  • eq()

后退

UpdateMany