文档菜单
文档首页
/ / /
Kotlin 协程
/ /

文档

本页内容

  • 概述
  • 文档
  • BsonDocument
  • JsonObject
  • 摘要

在本指南中,您可以了解如何在MongoDB Kotlin驱动程序中使用文档

MongoDB文档是一种包含二进制JSON(BSON)格式键/值字段的 数据结构。您可以使用文档及其字段中包含的数据来存储数据,以及在MongoDB中发布命令或查询。

有关术语、结构和文档的限制的更多信息,请参阅我们的关于文档页面。

MongoDB Kotlin驱动程序和BSON库包括以下类,可帮助您访问和操作文档中的BSON数据

名称
实现Map
推荐使用
文档
org.bson
是,实现了Map<String, Object>
当您需要一个灵活且简洁的数据表示时。
BsonDocument
org.bson
是,实现了Map<String, BsonValue>
当您需要一个类型安全的API时。
JsonObject
org.bson.json
当您只想处理JSON字符串时。

虽然您可以在应用程序中使用这些类中的任何一个,但我们建议您使用Document类,因为它可以简洁地表示任何复杂性的动态结构化文档。它实现了Map<String, Object>接口,使其能够使用松散类型的值。

Document类提供了一个灵活的BSON文档表示。您可以使用Kotlin标准库中的类型访问和操作字段。以下表格显示了常用BSON和Kotlin类型之间的映射

BSON类型
Kotlin类型
数组
kotlin.collections.List
二进制
org.bson.types.Binary
布尔
kotlin.Boolean
日期
java.time.LocalDateTime
文档
org.bson.Document
双精度浮点数
kotlin.Double
32位整数
kotlin.Int
64位整数
kotlin.Long
空值
null
ObjectId
org.bson.types.ObjectId
字符串
kotlin.String

以下代码片段展示了如何实例化和构建一个表示包含多种不同字段类型的示例Document实例的方法

val author = Document("_id", ObjectId())
.append("name", "Gabriel García Márquez")
.append(
"dateOfDeath",
LocalDateTime.of(2014, 4, 17, 4, 0)
)
.append(
"novels", listOf(
Document("title", "One Hundred Years of Solitude").append("yearPublished", 1967),
Document("title", "Chronicle of a Death Foretold").append("yearPublished", 1981),
Document("title", "Love in the Time of Cholera").append("yearPublished", 1985)
)
)

要将此文档插入集合中,请使用 getCollection() 方法实例化一个集合,并调用insertOne 操作,如下所示

// val mongoClient = <code to instantiate your client>
val database = mongoClient.getDatabase("fundamentals_data")
val collection = database.getCollection<Document>("authors")
val result = collection.insertOne(author)

成功执行插入操作后,您可以使用以下代码从集合中检索示例文档数据

val doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).firstOrNull()
doc?.let {
println("_id: ${it.getObjectId("_id")}, name: ${it.getString("name")}, dateOfDeath: ${it.getDate("dateOfDeath")}")
it.getList("novels", Document::class.java).forEach { novel ->
println("title: ${novel.getString("title")}, yearPublished: ${novel.getInteger("yearPublished")}")
}
}
_id: 5fb5fad05f734e3794741a35, name: Gabriel García Márquez, dateOfDeath: Thu Apr 17 00:00:00 EDT 2014
title: One Hundred Years of Solitude, yearPublished: 1967
title: Chronicle of a Death Foretold, yearPublished: 1981
title: Love in the Time of Cholera, yearPublished: 1985

提示

前面的代码示例使用了检查返回类型的辅助方法,如果无法转换字段值,则会抛出异常。您可以使用 get() 方法以 Object 类型检索值并跳过类型检查。

有关检索和操作 MongoDB 数据的更多信息,请参阅我们的 CRUD 指南。

有关本节中提到的方法和类的更多信息,请参阅以下 API 文档

BsonDocument 类提供了一个类型安全的 API,用于访问和操作 BSON 文档。您需要为每个字段指定来自 BSON 库的 BSON 类型。以下表格显示了常用 BSON 和 BSON 库类型之间的映射关系

BSON类型
BSON 库类型
数组
org.bson.BsonArray
二进制
org.bson.BsonBinary
布尔
org.bson.Boolean
Date(长整型值)
org.bson.BsonDateTime
文档
org.bson.BsonDocument
双精度浮点数
org.bson.BsonDouble
32位整数
org.bson.BsonInt32
64位整数
org.bson.BsonInt64
空值
org.bson.BsonNull
ObjectId
org.bson.BsonObjectId
字符串
org.bson.BsonString

在以下代码片段中,我们展示了如何实例化和构建一个表示包含几种不同字段类型的文档的 BsonDocument 实例

val author = BsonDocument()
.append("_id", BsonObjectId())
.append("name", BsonString("Gabriel García Márquez"))
.append(
"dateOfDeath",
BsonDateTime(
LocalDateTime.of(2014, 4, 17, 0, 0).atZone(ZoneId.of("America/New_York")).toInstant().toEpochMilli()
)
)
.append(
"novels", BsonArray(
listOf(
BsonDocument().append("title", BsonString("One Hundred Years of Solitude"))
.append("yearPublished", BsonInt32(1967)),
BsonDocument().append("title", BsonString("Chronicle of a Death Foretold"))
.append("yearPublished", BsonInt32(1981)),
BsonDocument().append("title", BsonString("Love in the Time of Cholera"))
.append("yearPublished", BsonInt32(1985))
)
)
)

要将此文档插入集合中,请使用 getCollection() 方法实例化一个集合,并将 BsonDocument 类指定为 documentClass 参数。然后,调用 insertOne 操作,如下所示

// val mongoClient = <code to instantiate your client>
val database = mongoClient.getDatabase("fundamentals_data")
val collection = database.getCollection<BsonDocument>("authors")
val result: InsertOneResult = collection.insertOne(author)

成功执行插入操作后,您可以使用以下代码从集合中检索示例文档数据

// <MongoCollection setup code here>
val doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).firstOrNull()
doc?.let {
println("_id: ${it.getObjectId("_id").value}, name: ${it.getString("name").value}, dateOfDeath: ${Instant.ofEpochMilli(it.getDateTime("dateOfDeath").value).atZone(ZoneId.of("America/New_York")).toLocalDateTime()}")
it.getArray("novels").forEach { novel ->
val novelDocument = novel.asDocument()
println("title: ${novelDocument.getString("title").value}, yearPublished: ${novelDocument.getInt32("yearPublished").value}")
}
}
_id: 5fb5fad05f734e3794741a35, name: Gabriel García Márquez, dateOfDeath: 2014-04-17T00:00
title: One Hundred Years of Solitude, yearPublished: 1967
title: Chronicle of a Death Foretold, yearPublished: 1981
title: Love in the Time of Cholera, yearPublished: 1985

提示

前面的代码示例使用了检查返回类型的辅助方法,如果无法转换字段值,则会抛出 BsonInvalidOperationException。您可以使用 get() 方法以 BsonValue 类型检索值并跳过类型检查。

有关本节中提到的方法和类的更多信息,请参阅以下 API 文档

JsonObject类作为JSON字符串的包装器。如果您只想处理JSON数据,可以使用JsonObject来避免将数据不必要地转换为Map对象。

默认情况下,JsonObject存储扩展JSON。您可以通过指定一个JsonObjectCodec和一个JsonWriterSettings对象来自定义JsonObject中的JSON格式。有关JSON格式的更多信息,请参阅我们的扩展JSON指南

以下代码片段展示了如何创建一个包含不同类型键值对的扩展JSON字符串的JsonObject实例。

val ejsonStr = """
{"_id": {"${"$"}oid": "6035210f35bd203721c3eab8"},
"name": "Gabriel García Márquez",
"dateOfDeath": {"${"$"}date": "2014-04-17T04:00:00Z"},
"novels": [
{"title": "One Hundred Years of Solitude","yearPublished": 1967},
{"title": "Chronicle of a Death Foretold","yearPublished": 1981},
{"title": "Love in the Time of Cholera","yearPublished": 1985}]}
""".trimIndent()
val author = JsonObject(ejsonStr)

要将此文档插入到集合中,请使用指定JsonObject类作为documentClass参数的getCollection()方法创建一个集合。然后,按照以下方式调用insertOne操作。

// val mongoClient = <code to instantiate your client>;
val database = mongoClient.getDatabase("fundamentals_data")
val collection= database.getCollection<JsonObject>("authors")
val result = collection.insertOne(author)

成功插入后,您可以从集合中检索示例JSON数据。虽然您可以使用任何扩展Bson的类来指定查询,但以下是使用JsonObject查询数据的方法。

// val mongoClient = <code to instantiate your client>;
val query = JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}")
val jsonResult = collection.find(query).firstOrNull()
jsonResult?.let {
println("query result in extended json format: " + jsonResult.json)
}
query result in extended json format: {"_id": {"$oid": "6035210f35bd203721c3eab8"}, "name": "Gabriel García Márquez", "dateOfDeath": {"$date": "2014-04-17T04:00:00Z"}, "novels": [{"title": "One Hundred Years of Solitude", "yearPublished": 1967}, {"title": "Chronicle of a Death Foretold", "yearPublished": 1981}, {"title": "Love in the Time of Cholera", "yearPublished": 1985}]}

有关本节中提到的方法和类的更多信息,请参阅以下 API 文档

在本指南中,我们介绍了以下与BSON数据相关的类:

  • 描述了可用于处理MongoDB文档的Kotlin类,以及为什么你可能更倾向于使用其中一个而不是另一个。

  • 为每个类提供了使用示例,包括构建包含多种类型的文档,将它们插入到集合中,以及检索/访问其类型字段。

返回

扩展JSON