Docs Menu
Docs Home
/ / /
Java 同期
/ / /

挿入操作

項目一覧

  • Overview
  • に関するメモ _id
  • 単一ドキュメントのインサート
  • 複数のドキュメントの挿入
  • 概要

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

MongoDB を使用して、情報を検索、更新、および削除できます。 これらの操作のいずれかを実行するには、ユーザー プロファイルや注文などの情報が MongoDB に存在する必要があります。 その情報を利用するには、まず挿入操作を実行する必要があります。

挿入操作では、 insertOne()insertMany()bulkWrite()メソッドを使用して、単一または複数のドキュメントを MongoDB に挿入します。

次のセクションでは、 insertOne()insertMany()に焦点を当てます。 bulkWrite()メソッドの使用方法について詳しくは、 一括操作 に関するガイドを参照してください。

ドキュメントを挿入する際、MongoDB はデフォルトでドキュメントに 1 つの制約を適用します。各ドキュメントには一意の_idフィールドが含まれている必要があります。

このフィールドを管理するには、次の 2 つの方法があります。

  • このフィールドは自分で管理し、使用する各値が一意であることを確認できます。

  • ドライバーが一意の ObjectId 値を自動的に生成できるようにします。

一意性について強力な保証を提供していない限り、ドライバーに_id値を自動的に生成させることをお勧めします。

注意

重複した_id値は一意のインデックス制約に違反し、 WriteErrorが返されます。

一意のインデックスに関する詳細については、「 一意のインデックス 」に関する手動エントリを参照してください。

単一のドキュメントを挿入する場合は、 insertOne()メソッドを使用します。

挿入に成功すると、メソッドは新しいドキュメントの_idを表すInsertOneResultインスタンスを返します。

次の例では、 insertOne()メソッドを使用してドキュメントを作成し、挿入します。

Document doc1 = new Document("color", "red").append("qty", 5);
InsertOneResult result = collection.insertOne(doc1);
System.out.println("Inserted a document with the following id: "
+ result.getInsertedId().asObjectId().getValue());

出力は次のようになります。

Inserted a document with the following id: 60930c39a982931c20ef6cd6

このセクションで述べられたメソッドとクラスの詳細については、次のリソースを参照してください。

複数のドキュメントを挿入する場合は、 insertMany()メソッドを使用します。 このメソッドは、例外が発生するまで、指定された順序でドキュメントを挿入します。

たとえば、次のドキュメントを挿入するとします。

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }
{ "_id": 3, "color": "yellow", "qty": 3 }
{ "_id": 6, "color": "blue", "qty": 8 }

これらのドキュメントを挿入しようとすると、3 番目のドキュメントでWriteErrorが発生し、エラーの前のドキュメントがコレクションに挿入されます。

Tip

エラーが発生する前に、正常に処理されたドキュメントの確認応答を取得するには、try-catch ブロックを使用します。

List<Integer> insertedIds = new ArrayList<>();
// Inserts sample documents and prints their "_id" values
try {
InsertManyResult result = collection.insertMany(documents);
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asInt32().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);
// Prints a message if any exceptions occur during the operation and the "_id" values of inserted documents
} catch(MongoBulkWriteException exception) {
exception.getWriteResult().getInserts()
.forEach(doc -> insertedIds.add(doc.getId().asInt32().getValue()));
System.out.println("A MongoBulkWriteException occurred, but there are " +
"successfully processed documents with the following ids: " + insertedIds);
}

出力は MongoDB が処理できるドキュメントで構成され、次のようになります。

A MongoBulkWriteException occurred, but there are successfully processed
documents with the following ids: [3, 4, 6]

コレクション内を確認すると、次のドキュメントが表示されます。

{ "_id": 3, "color": "red", "qty": 5 }
{ "_id": 4, "color": "purple", "qty": 10 }

挿入に成功すると、メソッドは新しい各ドキュメントの_idを表すInsertManyResultインスタンスを返します。

次の例では、2 つのドキュメントを作成してListに追加し、 insertMany()メソッドを使用してListを挿入します。

List<Document> documents = new ArrayList<>();
Document doc1 = new Document("color", "red").append("qty", 5);
Document doc2 = new Document("color", "purple").append("qty", 10);
documents.add(doc1);
documents.add(doc2);
InsertManyResult result = collection.insertMany(documents);
// Retrieves and prints the ID values of each inserted document
List<ObjectId> insertedIds = new ArrayList<>();
result.getInsertedIds().values()
.forEach(doc -> insertedIds.add(doc.asObjectId().getValue()));
System.out.println("Inserted documents with the following ids: " + insertedIds);

出力は次のようになります。

Inserted documents with the following ids: [60930c3aa982931c20ef6cd7, 60930c3aa982931c20ef6cd8]

このセクションで述べられたメソッドとクラスの詳細については、次のリソースを参照してください。

挿入操作を実行するには 3 つの方法がありますが、ここでは 2 つの方法に焦点を当てています。

  • insertOne()メソッドは 1 つのドキュメントを挿入します。

  • insertMany()メソッドは複数のドキュメントを挿入します。

ドキュメントで フィールドを省略すると、どちらの方法も_idを自動的に生成します。

挿入が成功した場合、両方のメソッドは新しい各ドキュメントの_idを表す インスタンスを返します。

戻る

書込み操作