Docs 菜单
Docs 主页
/ / /
Kotlin Sync 驱动程序
/

插入文档

在此页面上

  • 概述
  • 样本数据
  • _id 字段
  • 插入一个文档
  • 插入多个文档
  • 修改插入行为
  • 修改插入示例
  • 返回值
  • 更多信息
  • API 文档

在本指南中,您可以了解如何使用 Kotlin Sync 驱动程序通过执行插入操作将文档添加到 MongoDB 集合。

插入操作将一个或多个文档插入 MongoDB 集合。您可以使用 insertOne()insertMany()方法执行插入操作。

本指南中的示例使用 Atlas 样本数据集中sample_restaurants.restaurants集合。要了解如何创建免费的 MongoDB Atlas 集群并加载样本数据集,请参阅Atlas 入门指南。

此集合中的文档由以下 Kotlin 数据类建模:

data class Restaurant(val name: String, val borough: String)

在 MongoDB 集合中,每个文档都必须包含一个具有唯一值的_id字段。

MongoDB 允许您通过两种方式管理该字段:

  • 您可以自行为每个文档设置此字段,确保每个 _id 字段的值都是唯一的。

  • 您可以让驱动程序自动为每个文档_id生成唯一的ObjectId值。如果您没有为文档手动设置_id值,驱动程序将使用ObjectId填充该字段。

除非您可以保证唯一性,否则我们建议让驱动程序自动生成_id值。

注意

重复 _id 错误

在集合中设置重复的_id值违反了唯一索引约束,这会导致驱动程序从insertOne()方法返回WriteError或从insertMany()方法返回BulkWriteError

要了解有关_id字段的更多信息,请参阅 MongoDB Server 手册中的唯一索引指南。

要了解有关文档结构和规则的更多信息,请参阅 MongoDB Server 手册中的文档指南。

要将单个文档添加到 MongoDB 集合,请调用insertOne()方法并传递要添加的文档。

以下示例将文档插入restaurants集合:

val doc = Restaurant("Sea Shell Bar", "Queens")
val result = collection.insertOne(doc)

要将多个文档添加到 MongoDB 集合,请使用insertMany()方法并传递要添加的文档列表。

以下示例将文档列表插入restaurants集合:

val docs = listOf(
Restaurant("Full Moon Grill", "Queens"),
Restaurant("King's Cup", "Manhattan"),
)
val result = collection.insertMany(docs)

insertOne()方法可以选择接受InsertOneOptions参数,该参数设置用于配置插入操作的选项。如果不指定任何选项,驱动程序将使用默认设置执行插入操作。将选项作为最后一个参数传递给insertOne()方法。

下表描述了可用于配置InsertOneOptions实例的 setter 方法:

方法
说明
bypassDocumentValidation()
If set to true, allows the driver to ignore document-level validation.
Defaults to false.
comment()
Sets a comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual for more information.

您可以通过配置InsertManyOptions实例,在insertMany()方法上进行上述设置。您还可以使用ordered()方法 setter 方法来指定驱动程序将文档插入 MongoDB 的顺序:

方法
说明
ordered()
If set to true, the driver sends documents to the server in the order provided. If an error occurs, the driver cancels all remaining insert operations.
Defaults to true.

将选项作为最后一个参数传递给insertMany()方法。

以下代码使用bypassDocumentValidation()方法设置忽略文档验证规则的选项。然后,该示例使用insertMany()方法将新文档添加到restaurants集合。

val opts = InsertManyOptions().bypassDocumentValidation(true)
val docs = listOf(
Restaurant("Full Moon Grill", "Queens"),
Restaurant("King's Cup", "Manhattan"),
)
val result = collection.insertMany(docs, opts)

insertOne()方法返回InsertOneResult实例, insertMany()方法返回InsertManyResult实例。

您可以使用以下方法从InsertOneResult实例中检索信息:

方法
说明
getInsertedId()
指示插入文档的_id值。
wasAcknowledged()
如果服务器确认结果,则返回true

您可以使用以下方法从InsertOneResult实例中检索信息:

方法
说明
getInsertedIds()
指示插入文档的_id值。
wasAcknowledged()
如果服务器确认结果,则返回true

注意

如果wasAcknowledged()方法返回false ,则尝试访问_id值会导致InvalidOperation异常。如果服务器未确认写入操作,则驱动程序无法确定这些值。

有关演示如何使用 Kotlin Sync 驱动程序插入文档的可运行代码示例,请参阅将数据写入 MongoDB。

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

后退

将数据写入 MongoDB

来年

更新文档