Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Kotlin コルーチン
/ /

ドキュメント

このガイドでは、MongoDB Kotlin ドライバーでドキュメントを使用する方法を学習できます。

MongoDBドキュメントは、 バイナリJSON (BSON)形式のキーと値のフィールドを含むデータ構造です。 ドキュメントとそのフィールドに含まれるデータを使用してデータを保存し、それらを使用してMongoDBでコマンドやクエリを発行できます。

ドキュメントの用語、構造、制限の詳細については、MongoDB マニュアルのドキュメントに関するページをお読みください。

MongoDB Kotlin ドライバーと BSON ライブラリには、ドキュメント内の BSON データにアクセスして操作に役立つ次のクラスが含まれています。

名前
パッケージ
実装マップ
推奨使用量

Document

org.bson

はい、 を実装します Map<String, Object>

柔軟で簡潔なデータ表現が必要な場合。

BsonDocument

org.bson

はい、 を実装します Map<String, BsonValue>

型セーフな API が必要な場合。

JsonObject

org.bson.json

No

JSON string のみを操作する場合。

これらのクラスのいずれかをアプリケーションで使用できますが、動的に構造化されたドキュメントを簡潔に表現できるため、 Documentクラスを使用することをお勧めします。 緩やかに型指定された値を使用できるようにするMap<String, Object>インターフェースを実装しています。

Documentクラスは、BSON ドキュメントの柔軟な表現を提供します。 このクラスでは、標準ライブラリの Kotlin 型を使用してフィールドにアクセスし、操作できます。 頻繁に使用される BSON 型と Kotlin 型間のマッピングについては、次の表を参照してください。

BSON Type
Kotlin 型

配列

kotlin.collections.List

バイナリ

org.bson.types.Binary

ブール値

kotlin.Boolean

日付

java.time.LocalDateTime

ドキュメント

org.bson.Document

Double

kotlin.Double

Int32

kotlin.Int

Int64

kotlin.Long

null

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

Tip

上記のコード例では、返された型をチェックし、 フィールド値をキャストできない場合に例外をスローするヘルパー メソッドを使用しています。 get()メソッドを呼び出して、値をObject型として取得し、型チェックをスキップできます。

MongoDB データの取得と操作の詳細については、 CRUD ガイド をご覧ください。

このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。

BsonDocumentクラスは、BSON ドキュメントにアクセスして操作するための型セーフな API を提供します。 各フィールドに対して BSON ライブラリの BSON 型を指定する必要があります。 頻繁に使用される BSON と BSON ライブラリのタイプ間のマッピングについては、次の表を参照してください。

BSON Type
BSON ライブラリの種類

配列

org.bson.BsonArray

バイナリ

org.bson.BsonBinary

ブール値

org.bson.Boolean

日付(long 値)

org.bson.BsonDateTime

ドキュメント

org.bson.BsonDocument

Double

org.bson.BsonDouble

Int32

org.bson.BsonInt32

Int64

org.bson.BsonInt64

null

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

Tip

上記のコード例では、返された型をチェックし、フィールド値をキャストできない場合はBsonInvalidOperationExceptionをスローするヘルパー メソッドを使用しています。 get()メソッドを呼び出して、値をBsonValue型として取得し、型チェックをスキップできます。

このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。

JsonObjectクラスは JSON string のラッパーとして機能します。 JSON データのみを操作する場合は、 JsonObjectを使用してMapオブジェクトへの不要なデータ変換を回避できます。

デフォルトでは、 JsonObject拡張 JSONを保存します。 JsonObjectCodecを指定し、それにJsonWriterSettingsオブジェクトを渡すことで、 JsonObjectで JSON の形式をカスタマイズできます。 JSON 形式の詳細については、拡張 JSON ガイドをご覧ください。

次のコード スニペットは、さまざまなタイプのキーと値のペアを含む拡張 JSON string をラップするサンプルの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)

このドキュメントをコレクションに挿入するには、 getCollection()メソッドを使用してコレクションをインスタンス化し、 JsonObjectクラスをdocumentClassパラメータとして指定します。 次に、次のように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

項目一覧