ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

挿入操作

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

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

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

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

注意

The id_ Field in Insert Operations

When inserting a document, MongoDB enforces one constraint on your documents by default: each document する必要がある contain a unique _id value. Duplicate _id values violate unique index constraints, resulting in a WriteError.

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

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

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

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

For more information about unique indexes, see the manual entry on Unique Indexes.

単一のドキュメントを挿入する場合は、 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]

注意

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the MongoClient の作成 guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following code is a complete, standalone file that performs an insert one operation and an insert many operation:

// 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=...}}

For more information about the methods and classes used to insert documents, see the following API documentation: