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

插入文档

您可以使用 MongoCollection 对象上的insertOne()方法,将单个文档插入集合中。要插入文档,请构建一个 Document 对象,其中包含待存储的字段和值。若对一个尚不存在的集合调用 insertOne() 方法,服务器会自动创建该集合。

成功插入后,insertOne() 会返回 InsertOneResult 的实例。您可以通过对 InsertOneResult 实例调用 getInsertedId() 方法来检索信息,例如所插入文档的 _id 字段。

如果插入操作失败,驱动程序会引发异常。 有关特定条件下引发的异常类型的更多信息,请参阅本页底部链接的insertOne()的 API 文档。

以下代码片段用于在 movies 集合中插入单个文档。

运行该示例时,您应该会看到输出的 value 字段中包含插入文档的ObjectId

注意

此示例使用连接 URI 连接到MongoDB实例。 要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接指南。

import com.mongodb.MongoException
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.types.ObjectId
data class Movie(@BsonId val id: ObjectId, val title: String, val genres: List<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 result = collection.insertOne(
Movie(ObjectId(), "Ski Bloopers", listOf("Documentary", "Comedy"))
)
println("Success! Inserted document id: " + result.insertedId)
} catch (e: MongoException) {
System.err.println("Unable to insert due to an error: $e")
}
mongoClient.close()
}
Success! Inserted document id: BsonObjectId{value=...}

有关此页面上提及的类和方法的更多信息,请参阅以下 API 文档:

  • insertOne()

  • 文档

  • InsertOneResult

后退

Insert