Docs 菜单
Docs 主页
/ / /
Scala 驱动程序
/

插入文档

在此页面上

  • Overview
  • 样本数据
  • _id 字段
  • 插入一个文档
  • 插入多个文档
  • 修改插入行为
  • 例子
  • 更多信息

在本指南中,您可以学习;了解如何使用Scala驾驶员通过执行插入操作将文档添加到MongoDB集合。

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

  • insertOne() 插入单个文档

  • insertMany() 插入一个或多个文档

本指南中的示例使用restaurants sample_restaurantsAtlas示例数据集的 数据库中的 集合。要从Scala应用程序访问权限此集合,请创建一个连接到Atlas 集群的MongoClient,然后为 databasecollection 变量分配以下值:

val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants")
val collection: MongoCollection[Document] = database.getCollection("restaurants")

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

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

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

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

  • 让驾驶员自动为每个文档_id字段生成唯一的BsonObjectId值。

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

注意

重复的 _id 值违反了唯一索引约束,导致驾驶员返回错误。

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

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

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

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

val doc: Document = Document("name" -> "Neighborhood Bar & Grill", "borough" -> "Queens")
val observable: Observable[InsertOneResult] = collection.insertOne(doc)
observable.subscribe(new Observer[InsertOneResult] {
override def onNext(result: InsertOneResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertOneResult{insertedId=BsonObjectId{value=...}}
Completed

要将多个文档添加到MongoDB集合,请调用 insertMany() 函数并传递要插入的文档列表。

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

val docs: Seq[Document] = Seq(
Document("name" -> "Metropolitan Cafe", "borough" -> "Queens"),
Document("name" -> "Yankee Bistro", "borough" -> "Bronx")
)
val observable: Observable[InsertManyResult] = collection.insertMany(docs)
observable.subscribe(new Observer[InsertManyResult] {
override def onNext(result: InsertManyResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}}
Completed

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的顺序。 将选项作为最后一个参数传递给 insertMany() 方法。

以下代码使用 insertMany() 方法将三个新文档插入到集合中。 由于已启用 bypassDocumentValidation 选项,因此此插入操作会绕过文档级验证:

val docs: Seq[Document] = Seq(
Document("name" -> "One Night's Delight", "borough" -> "Queens"),
Document("name" -> "Second Street Pub", "borough" -> "Manhattan"),
Document("name" -> "Triple Crown Diner", "borough" -> "Brooklyn")
)
val opts: InsertManyOptions = InsertManyOptions().bypassDocumentValidation(true)
val observable: Observable[InsertManyResult] = collection.insertMany(docs, opts)
observable.subscribe(new Observer[InsertManyResult] {
override def onNext(result: InsertManyResult): Unit = println(result)
override def onError(e: Throwable): Unit = println("Failed: " + e.getMessage)
override def onComplete(): Unit = println("Completed")
})
AcknowledgedInsertManyResult{insertedIds={0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}, 2=BsonObjectId{value=...}}}
Completed

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

后退

写入数据