将数据写入 MongoDB
概述
在本页中,您可以查看可复制的代码示例,这些示例展示了您可以使用 Kotlin Sync 驱动器将数据写入 MongoDB 的常见方法。
提示
要了解更多关于本页上显示的任何方法,请参阅每个部分提供的链接。
要使用本页上的示例,请将代码示例复制到示例应用程序或您自己的应用程序中。请确保用您的 MongoDB 部署的相关值替换代码示例中的所有占位符,例如<连接字符串 URI>
。
示例应用程序
您可以使用以下示例应用程序来测试本页上的代码示例。要使用示例应用程序,请执行以下步骤
确保您的 Maven 或 Gradle 项目中已安装 Kotlin Sync 驱动器。
复制以下代码并将其粘贴到一个新的
.kt
文件中。从本页复制一个代码示例并将其粘贴到文件中的指定行。
1 import com.mongodb.ConnectionString 2 import com.mongodb.MongoClientSettings 3 import com.mongodb.client.model.* 4 import com.mongodb.kotlin.client.* 5 import org.bson.Document 6 7 fun main() { 8 val uri = "<connection string URI>" 9 10 val settings = MongoClientSettings.builder() 11 .applyConnectionString(ConnectionString(uri)) 12 .retryWrites(true) 13 .build() 14 15 // Create a new client and connect to the server 16 val mongoClient = MongoClient.create(settings) 17 val database = mongoClient.getDatabase("<database name>") 18 val collection = database.getCollection<Document>("<collection name>") 19 20 // Start example code here 21 22 // End example code here 23 }
插入一个
以下代码展示了如何将单个文档插入到集合中
val result = collection.insertOne(Document("<field name>", "<value>")) print(result.insertedId)
插入多个
以下代码展示了如何将多个文档插入到集合中
val docList = listOf( Document("<field name>", "<value>"), Document("<field name>", "<value>") ) val result = collection.insertMany(docList) print(result.insertedIds)
要了解更多关于 insertMany()
方法的信息,请参阅插入文档指南。
更新一个
以下代码展示了如何通过创建或编辑字段来更新集合中的一个文档
val query = Filters.eq("<field to match>", "<value to match>") val update = Updates.set("<field name>", "<value>") val result = collection.updateOne(query, update) print(result.modifiedCount)
要了解更多关于 updateOne()
方法的信息,请参阅更新文档指南。
更新多个
以下代码展示了如何通过创建或编辑字段来更新集合中的多个文档。
val query = Filters.eq("<field to match>", "<value to match>") val update = Updates.set("<field name>", "<value>") val result = collection.updateMany(query, update) print(result.modifiedCount)
要了解更多关于 updateMany()
方法的知识,请参阅更新文档指南。
替换一个
以下代码展示了如何用一个新文档替换集合中的一个文档。
val query = Filters.eq("<field to match>", "<value to match>") val replacement = Document("<new document field name>", "<new document value>") val result = collection.replaceOne(query, replacement) print(result.modifiedCount)
要了解更多关于 replaceOne()
方法的知识,请参阅替换文档指南。
删除一个
以下代码展示了如何删除集合中的一个文档。
val query = Filters.eq("<field to match>", "<value to match>") val result = collection.deleteOne(query) print(result.deletedCount)
要了解更多关于 deleteOne()
方法的知识,请参阅删除文档指南。
删除多个
以下代码演示了如何在集合中删除多个文档
val query = Filters.eq("<field to match>", "<value to match>") val result = collection.deleteMany(query) print(result.deletedCount)
要了解有关 deleteMany()
方法的更多信息,请参阅删除文档指南。
批量写入
以下代码演示了如何在单个批量操作中执行多个写入操作
val bulkOps = listOf( InsertOneModel(Document("<field name>", "<value>")), UpdateOneModel( Filters.eq("<field to match>", "<value to match>"), Updates.set("<field name>", "<value>")), DeleteOneModel(Filters.eq("<field to match>", "<value to match>")) ) val result = collection.bulkWrite(bulkOps) print(result)
要了解有关 bulkWrite()
方法的更多信息,请参阅批量写入指南。