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

连接至 MongoDB

1

在项目中创建一个名为 DemoDataClassExample.kt的文件。

将以下示例代码复制到该文件中,并将<connection URI string>占位符的值替换为您在上一步中保存的 MongoDB Atlas 连接字符串。

DemoDataClassExample.kt
import com.mongodb.client.model.Filters.eq
import com.mongodb.kotlin.client.MongoClient
// Create data class to represent a MongoDB document
data class Movie(val title: String, val year: Int, val directors: List<String>)
fun main() {
// Replace the placeholder with your MongoDB deployment's connection string
val uri = "<connection URI string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Movie>("movies")
// Find a document with the specified title
val doc = collection.find(eq(Movie::title.name, "Before Sunrise")).firstOrNull()
if (doc != null) {
// Print the matching document
println(doc)
} else {
println("No matching documents found.")
}
}

注意

此示例使用 Kotlin 数据类对 MongoDB 数据建模。

2

运行应用程序时,它会打印与查询匹配的电影文档的详细信息,如以下输出所示:

Movie(title=Before Sunrise, year=1995, directors=[Richard Linklater])

如果未看到任何输出或收到错误,请检查应用程序中是否包含正确的连接字符串。另外,确认您已成功将示例数据集加载到 MongoDB Atlas 集群中。

完成此步骤后,您就拥有一个正常运行的应用程序,它使用 Kotlin Sync 驱动程序连接到 MongoDB 集群、对示例数据运行查询并打印结果。

3

前面的步骤演示了如何使用 Kotlin 数据类对示例集合运行查询以检索数据。本部分介绍如何使用 文档 类以在 MongoDB 中存储和检索数据。

在名为DemoDocumentExample.kt的文件中,粘贴以下示例代码,对 MongoDB Atlas 中的示例数据集运行查询。将<connection URI string>占位符的值替换为 MongoDB Atlas 连接字符串:

DemoDocumentExample.kt
import com.mongodb.client.model.Filters.eq
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
fun main() {
// Replace the placeholder with your MongoDB deployment's connection string
val uri = "<connection URI string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
// Find a document with the specified title
val doc = collection.find(eq("title", "Before Sunrise")).firstOrNull()
if (doc != null) {
// Print the matching document
println(doc)
} else {
println("No matching documents found.")
}
}

运行应用程序时,它会打印与查询匹配的电影文档的详细信息,如以下输出所示:

Document{{_id=..., plot=A young man and woman ..., genres=[Drama, Romance], ...}}

如果未看到任何输出或收到错误,请检查应用程序中是否包含正确的连接字符串。另外,确认您已成功将示例数据集加载到 MongoDB Atlas 集群中。

完成这些步骤后,您有一个正常运行的应用程序,它使用驱动程序连接到 MongoDB 部署、对示例数据运行查询并打印结果。

注意

如果您在该步骤中遇到问题,请在 MongoDB 社区论坛中寻求帮助,或使用本页右侧或右下角的 Rate this page(本页内容评级)标签页提交反馈。

后退

创建连接字符串