插入操作
概述
在本指南中,您可以学习如何使用MongoDB Kotlin驱动程序插入文档。
您可以使用MongoDB检索、更新和删除信息。要执行这些操作中的任何一项,该信息,例如用户资料和订单,需要存在于MongoDB中。为了使这些信息存在,您需要首先执行插入操作。
插入操作通过以下方法将单个或多个文档插入MongoDB:insertOne()
、insertMany()
和bulkWrite()
方法。
以下几节重点介绍insertOne()
和insertMany()
方法。有关如何使用bulkWrite()
方法的更多信息,请参阅我们的批量操作指南.
以下示例中,一家油漆店拥有不同颜色的油漆库存。该数据使用以下Kotlin数据类进行建模
data class PaintOrder( val id: ObjectId? = null, val qty: Int, val color: String )
关于_id
的注意事项
当插入文档时,MongoDB默认对您的文档施加一个约束:每个文档必须包含一个唯一的_id
字段。
有两种方式来管理此字段
您可以自己管理此字段,确保您使用的每个值都是唯一的。
您可以允许驱动程序自动生成唯一的ObjectId值。
除非您提供了唯一性的强保证,否则我们建议您让驱动程序自动生成_id
值。
注意
重复的_id
值违反了唯一索引约束,导致WriteError
。
有关唯一索引的更多信息,请参阅唯一索引的手册条目.
插入单个文档
当您想要插入单个文档时,请使用insertOne()
方法。
在插入成功后,该方法返回一个表示新文档_id
的InsertOneResult
实例。
示例
以下示例使用insertOne()
方法创建并插入文档
val paintOrder = PaintOrder(ObjectId(), 5, "red") val result = collection.insertOne(paintOrder) val insertedId = result.insertedId?.asObjectId()?.value println("Inserted a document with the following id: $insertedId")
Inserted a document with the following id: 60930c39a982931c20ef6cd6
有关本节中提到的方法和类的更多信息,请参阅以下资源
insertOne() API 文档
InsertOneResult API 文档
关于
insertOne()
的手动说明insertOne()可运行的
插入文档示例
Insert a Document example
插入多个文档
当您想要插入多个文档时,请使用 insertMany()
方法。此方法按指定顺序插入文档,直到发生异常(如果有)。
例如,假设您想要插入以下文档
{ "color": "red", "qty": 5 } { "color": "purple", "qty": 10 } { "color": "yellow", "qty": 3 } { "color": "blue", "qty": 8 }
如果您尝试插入这些文档,第三个文档将引发一个 WriteError
,错误之前的文档将插入到您的集合中。
提示
使用 try-catch 块在错误发生之前获取已成功处理的文档的确认。输出包括 MongoDB 可以处理的文档
val result = collection.insertMany(paintOrders) try { println("Inserted documents with the following ids: ${result.insertedIds}") } catch(e: MongoBulkWriteException){ val insertedIds = e.writeResult.inserts.map { it.id.asInt32().value } println( "A MongoBulkWriteException occurred, but there are " + "successfully processed documents with the following ids: $insertedIds" ) collection.find().collect { println(it) } }
A MongoBulkWriteException occurred, but there are successfully processed documents with the following ids: [60930c3aa982931c20ef6cd7, 644ad1378ea29443837a14e9, 60930c3aa982931c20ef6cd8]
如果您查看您的集合,您应该看到以下文档
{ "color": "red", "qty": 5 } { "color": "purple", "qty": 10 }
在成功插入后,该方法返回一个表示每个新文档的 _id
的 InsertManyResult
实例。
示例
以下示例创建并添加两个文档到 List
,然后使用 insertMany()
方法插入 List
val paintOrders = listOf( PaintOrder(ObjectId(), 5, "red"), PaintOrder(ObjectId(), 10, "purple") ) val result = collection.insertMany(paintOrders) println("Inserted a document with the following ids: ${result.insertedIds.toList()}")
Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]
有关本节中提到的方法和类的更多信息,请参阅以下资源
insertMany() API 文档
InsertManyResult API 文档
关于 insertMany() 的手动解释
可运行的 插入多个文档示例
摘要
执行插入操作有三种方式,但我们只关注两种
insertOne()
方法用于插入单个文档。insertMany()
方法用于插入多个文档。
如果您的文档中省略了该字段,两种方法都会自动生成一个 _id
。
如果插入成功,两种方法都会返回表示每个新文档 _id
的实例。