Overview
このガイドでは、MongoDB Java ドライバーを使用してドキュメントを 挿入 する方法を学習できます。
MongoDB を使用して、情報を検索、更新、および削除できます。 これらの操作のいずれかを実行するには、ユーザー プロファイルや注文などの情報が MongoDB に存在する必要があります。 その情報を存在させるには、まず挿入操作を実行します。
挿入操作では、 insertOne() 、 insertMany() 、 bulkWrite()メソッドを使用して、単一または複数のドキュメントを MongoDB に挿入します。
次のセクションでは、 insertOne()とinsertMany()に焦点を当てます。 bulkWrite()メソッドの使用方法について詳しくは、 一括操作 に関するガイドをご覧ください。
注意
挿入操作における id_ フィールド
ドキュメントを挿入する場合、 MongoDB はデフォルトで 1 つの制約をドキュメントに適用します。各ドキュメントには一意の _id 値が含まれている必要があります。重複した _id 値はユニークインデックス制約に違反し、WriteError が返されます。
このフィールドを管理するには、次の 2 つの方法があります。
このフィールドは自分で管理し、使用する各値が一意であることを確認できます。
ドライバーが一意の ObjectId 値を自動的に生成できるようにします。
一意性について強力な保証を提供していない限り、ドライバーに_id値を自動的に生成させることをお勧めします。
一意なインデックスの詳細については、一意なインデックスに関するマニュアル エントリを参照してください。
単一ドキュメントのインサート
単一のドキュメントを挿入する場合は、 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このセクションで述べられたメソッドとクラスの詳細については、次のリソースを参照してください。
insertOne() APIドキュメント
InsertOneResult APIドキュメント
insertOne()に関する手動説明
複数のドキュメントの挿入
複数のドキュメントを挿入する場合は、 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" valuestry { 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 processeddocuments 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 documentList<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]挿入例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB の開始方法に従って、MongoDB Atlas の無料クラスター上のデータベースに読み込むことができます。
次のコードは、1 つの挿入操作と の挿入操作を実行する完全なスタンドアロンファイルです。
// Inserts a sample document describing a movie by using the Java driver
package org.example;
import java.util.Arrays;
import org.bson.Document;import org.bson.types.ObjectId;
import com.mongodb.MongoException;import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoDatabase;import com.mongodb.client.result.InsertOneResult;import com.mongodb.client.result.InsertManyResult;
import java.util.List;
public class Insert { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies");
// Inserts a sample document describing a movie into the collection InsertOneResult result = collection.insertOne(new Document() .append("_id", new ObjectId()) .append("title", "Ski Bloopers") .append("genres", Arrays.asList("Documentary", "Comedy")));
// Prints the ID of the inserted document System.out.println("Inserted document id - insert one: " + result.getInsertedId());
// Creates two sample documents containing a "title" field List<Document> movieList = Arrays.asList( new Document().append("title", "Short Circuit 3"), new Document().append("title", "The Lego Frozen Movie"));
// Inserts sample documents describing movies into the collection InsertManyResult result = collection.insertMany(movieList);
// Prints the IDs of the inserted documents System.out.println("Inserted document id - insert many: " + result.getInsertedIds()); } }}トラブルシューティング
書込み (write) 例外
ドライバーは、単一の書込み操作を実行するときに発生する書込みエラーに対して MongoWriteException をスローします。MongoWriteExceptionオブジェクトには、その原因である WriteErrorオブジェクトを含む errorフィールドがあります。
quantityフィールドの値が int 型である必要があるスキーマ検証ルール を持つコレクションを考えてみましょう。次の例では、quantity の値が "three" であるドキュメントを挿入しようとすると、ドライバーは MongoWriteException をスローします。
Exception in thread "main" com.mongodb.MongoWriteException: Document failed validation atcom.mongodb.internal.connection.ProtocolHelper.getWriteException(ProtocolHelper.java:228)...Caused by: com.mongodb.MongoWriteException: WriteError{code=121,message='Document failed validation', details={ operator: "$jsonSchema",schemaRules: { bsonType: "int", description: "must be an integer" },offendingDocument: {"name":"Apple","quantity":"three"} } } atcom.mongodb.internal.connection.WriteResultHelper.createWriteException(WriteResultHelper.java:50)スキーマ検証の詳細については、 サーバー マニュアル エントリ セクションの「 スキーマバリデーション 」を参照してください。
詳細情報
API ドキュメント
ドキュメントの挿入に使用されるメソッドとクラスの詳細については、次のAPIドキュメントを参照してください。
「 トラブルシューティング 」セクションで説明されているエラーの種類の詳細については、次のAPIドキュメントを参照してください。