文档菜单
文档首页
/ / /
Kotlin 同步驱动程序
/

连接到 MongoDB

1

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

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

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 数据类在示例集合上运行查询以检索数据。本节将展示如何使用Document 类来存储和检索 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 社区论坛 中寻求帮助或通过使用此页面的右侧或右下角的评分此页面 选项卡提交反馈。

返回

创建连接字符串