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" 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]
挿入例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、MongoClient の作成 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflix
データベースの movies
コレクションも使用します。「Atlas を使い始める」ガイドに従って、 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()); } } }
insertOne() document id: BsonObjectId{value=...} insertMany() document ids: {0=BsonObjectId{value=...}, 1=BsonObjectId{value=...}}
トラブルシューティング
書込み (write) 例外
ドライバーは、単一の書込み操作を実行するときに発生する書込みエラーに対して MongoWriteException をスローします。MongoWriteException
オブジェクトには、その原因であるerror
WriteError
オブジェクトを含む フィールドがあります。
quantity
フィールドの値が int
型である必要があるスキーマ検証ルール を持つコレクションを考えてみましょう。次の例では、quantity
の値が "three"
であるドキュメントを挿入しようとすると、ドライバーは MongoWriteException
をスローします。
Exception in thread "main" com.mongodb.MongoWriteException: Document failed validation at com.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"} } } at com.mongodb.internal.connection.WriteResultHelper.createWriteException(WriteResultHelper.java:50)
スキーマ検証の詳細については、 サーバー マニュアル エントリ セクションの「 スキーマバリデーション 」を参照してください。
詳細情報
API ドキュメント
ドキュメントの挿入に使用されるメソッドとクラスの詳細については、次のAPIドキュメントを参照してください。
「 トラブルシューティング 」セクションで説明されているエラーの種類の詳細については、次のAPIドキュメントを参照してください。