Docs 菜单

插入文档

您可以使用对象上的insertOne() MongoCollection方法将文档插入到collection中。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 文档: