Overview
このガイドでは、MongoDB Java ドライバーでドキュメントを使用する方法を学習できます。
MongoDB ドキュメントは、バイナリ JSON(BSON)形式のキーと値フィールドを含むデータ構造です。 MongoDB では、ドキュメントとそのフィールドに含まれるデータを使用してデータを保存し、コマンドやクエリを発行できます。
ドキュメントの用語、構造、制限の詳細については、MongoDB マニュアルのドキュメントに関するページをお読みください。
MongoDB Java ドライバーと BSON ライブラリには、ドキュメント内の BSON データにアクセスして操作に役立つ次のクラスが含まれています。
名前 | パッケージ | 実装マップ | 推奨使用量 |
|---|---|---|---|
|
| はい、 を実装します | 柔軟で簡潔なデータ表現が必要な場合。 |
|
| はい、 を実装します | 型セーフな API が必要な場合。 |
|
| No | JSON string のみを操作する場合。 |
|
| No | アプリケーションをレガシーのドライバー バージョンから移行する場合。 |
これらのクラスのいずれかをアプリケーションで使用できますが、動的に構造化されたドキュメントを簡潔に表現できるため、 Documentクラスを使用することをお勧めします。 緩やかに型指定された値を使用できるようにするMap<String, Object>インターフェースを実装しています。
ドキュメント
Documentクラスは、BSON ドキュメントの柔軟な表現を提供します。 このクラスでは、標準ライブラリの Java 型を使用してフィールドにアクセスし、操作できます。 頻繁に使用される BSON 型と Java 型の間のマッピングについては、次の表を参照してください。
BSON Type | Java 型 |
|---|---|
配列 |
|
バイナリ |
|
ブール値 |
|
日付 |
|
ドキュメント |
|
Double |
|
Int32 |
|
Int64 |
|
null |
|
ObjectId |
|
文字列 |
|
上記のマッピング表は、 Documentクラスを操作する場合のデフォルトのマッピングを示しています。 カスタム コーデックを指定することで、型マッピングをカスタマイズできます。 マップされた型をカスタマイズする方法の詳細については、 コーデックの使用に関するガイドを参照してください。
次のコード スニペットは、複数の異なるフィールド型を含むドキュメントを表すサンプルのDocumentインスタンスをインスタンス化して構築する方法を示しています。
Document author = new Document("_id", new ObjectId()) .append("name", "Gabriel García Márquez") .append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()).toInstant())) .append("novels", Arrays.asList( new Document("title", "One Hundred Years of Solitude") .append("yearPublished", 1967), new Document("title", "Chronicle of a Death Foretold") .append("yearPublished", 1981), new Document("title", "Love in the Time of Cholera") .append("yearPublished", 1985)));
このドキュメントをコレクションに挿入するには、 getCollection()メソッドを使用してコレクションをインスタンス化し、次のようにinsertOne操作を呼び出します。
// MongoClient mongoClient = <code to instantiate your client>; MongoDatabase database = mongoClient.getDatabase("fundamentals_data"); MongoCollection<Document> collection = database.getCollection("authors"); InsertOneResult result = collection.insertOne(author);
挿入が成功すると、次のコードを使用して コレクションからサンプル ドキュメント データを検索できます。
import com.mongodb.client.model.Filters; // <MongoCollection setup code here> Document doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first(); if (doc != null) { System.out.println("_id: " + doc.getObjectId("_id") + ", name: " + doc.getString("name") + ", dateOfDeath: " + doc.getDate("dateOfDeath")); doc.getList("novels", Document.class).forEach((novel) -> { System.out.println("title: " + novel.getString("title") + ", yearPublished: " + novel.getInteger("yearPublished")); }); }
Tip
上記のコード例では、返された型をチェックし、 フィールド値をキャストできない場合に例外をスローするヘルパー メソッドを使用しています。 Mapインターフェースで指定されたget()メソッドを呼び出して、フィールド値をObject型として取得し、型チェックをスキップできます。
上記のコードの出力は、次のようになります。
_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
MongoDB データの取得と操作の詳細については、 CRUD ガイド をご覧ください。
このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。
BsonDocument
BsonDocumentクラスは、BSON ドキュメントにアクセスして操作するための型セーフな API を提供します。 各フィールドに対して Java BSON ライブラリから BSON 型を指定する必要があります。 頻繁に使用される BSON と Java BSON ライブラリのタイプ間のマッピングについては、次の表を参照してください。
BSON Type | Java BSON ライブラリの型 |
|---|---|
配列 |
|
バイナリ |
|
ブール値 |
|
日付(long 値) |
|
ドキュメント |
|
Double |
|
Int32 |
|
Int64 |
|
null |
|
ObjectId |
|
文字列 |
|
次のコード スニペットは、複数の異なるフィールド型を含むドキュメントを表すサンプルのBsonDocumentインスタンスをインスタンス化して構築する方法を示しています。
BsonDocument author = new BsonDocument() .append("_id", new BsonObjectId()) .append("name", new BsonString("Gabriel García Márquez")) .append("dateOfDeath", new BsonDateTime(LocalDate.of(2014, 4, 17).atStartOfDay(ZoneId.systemDefault()) .toInstant().toEpochMilli())) .append("novels", new BsonArray(Arrays.asList( new BsonDocument().append("title", new BsonString("One Hundred Years of Solitude")) .append("yearPublished", new BsonInt32(1967)), new BsonDocument().append("title", new BsonString("Chronicle of a Death Foretold")) .append("yearPublished", new BsonInt32(1981)), new BsonDocument().append("title", new BsonString("Love in the Time of Cholera")) .append("yearPublished", new BsonInt32(1985)) )));
このドキュメントをコレクションに挿入するには、 getCollection()メソッドを使用してコレクションをインスタンス化し、 BsonDocumentクラスをdocumentClassパラメータとして指定します。 次に、次のようにinsertOne操作を呼び出します。
// MongoClient mongoClient = <code to instantiate your client>; MongoDatabase database = mongoClient.getDatabase("fundamentals_data"); MongoCollection<BsonDocument> collection = database.getCollection("authors", BsonDocument.class); InsertOneResult result = collection.insertOne(author);
挿入が成功すると、次のコードを使用して コレクションからサンプル ドキュメント データを検索できます。
import com.mongodb.client.model.Filters; // <MongoCollection setup code here> BsonDocument doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first(); if (doc != null) { System.out.println("_id: " + doc.getObjectId("_id").getValue() + ", name: " + doc.getString("name").getValue() + ", dateOfDeath: " + new Date(doc.getDateTime("dateOfDeath").getValue())); doc.getArray("novels").forEach((novel) -> { System.out.println("title: " + novel.asDocument().getString("title").getValue() + ", yearPublished: " + novel.asDocument().getInt32("yearPublished").getValue()); }); }
Tip
上記のコード例では、返された型をチェックし、フィールド値をキャストできない場合はBsonInvalidOperationExceptionをスローするヘルパー メソッドを使用しています。 Mapインターフェースで指定されたget()メソッドを呼び出して、フィールド値をBsonValue型として取得し、型チェックをスキップできます。
上記のコードの出力は、次のようになります。
_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
このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。
JsonObject
JsonObjectクラスは JSON string のラッパーとして機能します。 JSON データのみを操作する場合は、 JsonObjectを使用してMapオブジェクトへの不要なデータ変換を回避できます。
デフォルトでは、 JsonObjectは拡張 JSONを保存します。 JsonObjectCodecを指定し、それにJsonWriterSettingsオブジェクトを渡すことで、 JsonObjectで JSON の形式をカスタマイズできます。 JSON 形式の詳細については、拡張 JSON ガイドをご覧ください。 コーデックの指定の詳細については、コーデック ガイドを参照してください。
次のコード スニペットは、さまざまなタイプのキーと値のペアを含む拡張 JSON string をラップするサンプルのJsonObjectインスタンスをインスタンス化する方法を示しています。
String ejsonStr = "{\"_id\": {\"$oid\": \"6035210f35bd203721c3eab8\"}," + "\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"," + "\"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}]}"; JsonObject author = new JsonObject(ejsonStr);
このドキュメントをコレクションに挿入するには、 getCollection()メソッドを使用してコレクションをインスタンス化し、 JsonObjectクラスをdocumentClassパラメータとして指定します。 次に、次のようにinsertOne操作を呼び出します。
// MongoClient mongoClient = <code to instantiate your client>; MongoDatabase database = mongoClient.getDatabase("fundamentals_data"); MongoCollection<JsonObject> collection = database.getCollection("authors", JsonObject.class); InsertOneResult result = collection.insertOne(author);
挿入が正常に実行されると、 コレクションからサンプル JSON データを取得できます。 Bsonを拡張する任意のクラスを使用してクエリを指定できますが、次はJsonObjectを使用してデータをクエリする方法です。
// MongoClient mongoClient = <code to instantiate your client>; JsonObject query = new JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}"); JsonObject jsonResult = collection.find(query).first(); if (jsonResult != null) { System.out.println("query result in extended json format: " + jsonResult.getJson()); }
上記のコードの出力は、次のようになります。
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}]}
Tip
アプリケーション内で他の形式の JSON string を使用する場合は、 JsonObjectCodecクラスとJsonWriterSettingsを使用して、必要な JSON 形式を指定できます。
次のコード例では、緩和モードの JSON string を使用して MongoDB インスタンスの読み取りと書き込みを行い、 ObjectIdインスタンスを 16 進文字列として出力します。
import static org.bson.codecs.configuration.CodecRegistries.fromCodecs; // MongoClient mongoClient = <code to instantiate your client>; MongoDatabase database = mongoClient.getDatabase("fundamentals_data"); MongoCollection<JsonObject> collection = database.getCollection("authors", JsonObject.class) .withCodecRegistry( fromCodecs( // define a JsonObjectCodec with a JsonWriterSettings in Relaxed mode new JsonObjectCodec(JsonWriterSettings .builder() .outputMode(JsonMode.RELAXED) .objectIdConverter((objectId, strictJsonWriter) -> { strictJsonWriter.writeString(objectId.toHexString()); }) .build()))); JsonObject author = new JsonObject("{\"_id\": \"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}]}\n"); collection.insertOne(author); JsonObject query = new JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}"); JsonObject jsonResult = collection.find(query).first(); if (jsonResult != null) { System.out.println("query result in relaxed json format: " + jsonResult.getJson()); }
上記のコードの出力は、次のようになります。
query result in relaxed json format: {"_id": "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 ドキュメントを参照してください。
基本DBObject
BasicDBObjectクラスでは、Java 型を使用してドキュメント データにアクセスし、操作できます。 次の制限があるため、古いドライバー バージョンからアプリケーションを移行する場合を除き、このクラスの使用を避けることをお勧めします。
BasicDBObjectはMap<K, V>を実装していないため、Mapのデータアクセスと操作の便利なメソッドがありません。クラスではなく
DBObjectインターフェースが実装されているため、バイナリ互換性 を中断せずにAPIを拡張することはできません。つまり、インターフェースが変更されてバイナリの互換性がなくなった場合、エラーなく新しいバージョンを実行するには、インターフェースを使用するすべてのアプリケーションとクラスを再コンパイルする必要があります。
次のコード スニペットは、複数の異なるフィールド型を含むドキュメントを表すサンプルのBasicDBObjectインスタンスをインスタンス化して構築する方法を示しています。
BasicDBObject author = new BasicDBObject("_id", new ObjectId()) .append("name", "Gabriel García Márquez") .append("dateOfDeath", Date.from(LocalDate.of(2014, 4, 17) .atStartOfDay(ZoneId.systemDefault()).toInstant())) .append("novels", Arrays.asList( new BasicDBObject("title", "One Hundred Years of Solitude") .append("yearPublished", 1967), new BasicDBObject("title", "Chronicle of a Death Foretold") .append("yearPublished", 1981), new BasicDBObject("title", "Love in the Time of Cholera") .append("yearPublished", 1985)));
このドキュメントをコレクションに挿入するには、 getCollection()メソッドを使用してコレクションをインスタンス化し、 BasicDBObjectクラスをdocumentClassパラメータとして指定します。 次に、次のようにinsertOne操作を呼び出します。
// MongoClient mongoClient = <code to instantiate your client>; MongoDatabase database = mongoClient.getDatabase("fundamentals_data"); MongoCollection<BasicDBObject> collection = database.getCollection("authors", BasicDBObject.class); InsertOneResult result = collection.insertOne(author);
挿入が成功すると、次のコードを使用して コレクションからサンプル ドキュメント データを検索できます。
import com.mongodb.client.model.Filters; // <MongoCollection setup code here> BasicDBObject doc = collection.find(Filters.eq("name", "Gabriel García Márquez")).first(); if (doc != null) { System.out.println("_id: " + doc.getObjectId("_id") + ", name: " + doc.getString("name") + ", dateOfDeath: " + doc.getDate("dateOfDeath")); BasicDBList novels = (BasicDBList) doc.get("novels"); if (novels != null) { BasicDBObject[] novelArr = novels.toArray(new BasicDBObject[0]); for (BasicDBObject novel : novelArr) { System.out.println("title: " + novel.getString("title") + ", yearPublished: " + novel.getInt("yearPublished")); } } }
Tip
上記のコード例では、返された型をチェックし、 フィールド値をキャストできない場合に例外をスローするヘルパー メソッドを使用しています。 get()メソッドを呼び出して、値をObject型として取得し、型チェックをスキップできます。
上記のコードの出力は、次のようになります。
_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
このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。
概要
このガイドでは、 BSON データを操作するために使用できるクラスに関する次のトピックについて説明しました。
MongoDB ドキュメントを操作するために使用できる 4 つの Java クラスと、どちらか一方を優先する理由について説明します。
複数のタイプを含むドキュメントの作成、コレクションへの挿入、それらの型付きフィールドの検索/アクセスに関する各クラスの使用例を提供しました。