AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

ドキュメントの挿入

このガイドでは、MongoDB にドキュメントを 挿入 する方法を学習できます。

MongoDB を使用して、MongoDB にすでに保存されている情報を検索、更新、および削除できます。 情報を保存するには、挿入操作を使用します。

挿入操作は、1 つ以上のドキュメントを MongoDB コレクションに挿入します。 Node.js ドライバーは、挿入操作を実行するための次のメソッドを提供します。

  • insertOne()

  • insertMany()

  • bulkWrite()

Tip

インタラクティブ ラボ

このページには、 insertOne()メソッドを使用してデータを挿入する方法を示す短いインタラクティブ ラボが含まれています。 MongoDB やコード エディターをインストールしなくても、ブラウザ ウィンドウでこのラボを直接完了できます。

ラボを開始するには、ページ上部の [ Open Interactive Tutorial ] ボタンをクリックします。 ラボを全画面形式に展開するには、ラボ ペインの右上隅にある全画面ボタン( ⛶ )をクリックします。

次のセクションでは、insertOne() と insertMany() に焦点を当てます。bulkWrite()メソッドの使用方法の例については、 一括操作ガイドの「 bulkWrite() の例: 完全なファイル 」セクションを参照してください。

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

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

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

  • ドライバーはプライマリキー ファクトリを使用して一意のObjectId値を自動的に生成できます。

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

注意

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

_idの詳細については、一意なインデックス に関するサーバー マニュアルのエントリを参照してください。

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

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

次の例では、 insertOne()メソッドを使用して新しいドキュメントをmyDB.pizzaMenuコレクションに挿入しています。

const myDB = client.db("myDB");const myColl = myDB.collection("pizzaMenu"); const doc = { name: "Neapolitan pizza", shape: "round" };const result = await myColl.insertOne(doc);console.log( `A document was inserted with the _id: ${result.insertedId}`,);

出力は、次のテキストのようになります。

A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836

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

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoDB への接続」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB Get Startedに従って、MongoDB Atlasの無料クラスター上のデータベースに読み込むことができます。

次のコードは、1 つの挿入操作を実行する完全なスタンドアロンファイルです。

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>"; // Create a new client and connect to MongoDBconst client = new MongoClient(uri); async function run() { try { // Connect to the "sample_mflix" database and access its "movies" collection const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a document to insert const doc = { title: "Charade", genres: ["Comedy", "Romance", "Thriller"], year: 1963, cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], } // Insert the defined document into the "movies" collection const result = await movies.insertOne(doc); // Print the ID of the inserted document console.log(`A document was inserted with the _id: ${result.insertedId}`); } finally { // Close the MongoDB client connection await client.close(); }}// Run the function and handle any errorsrun().catch(console.dir);

上記の例を実行すると、次の出力が生成されます。

A document was inserted with the _id: ...

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

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

{ "_id": 1, "color": "red" }{ "_id": 2, "color": "purple" }{ "_id": 1, "color": "yellow" }{ "_id": 3, "color": "blue" }

上記のドキュメントを insertMany() メソッドに渡すと、ドライバーは 1 番目と 2 番目のドキュメントを挿入しますが、 ID 1 が重複しているため、3 番目のドキュメントでは WriteError がスローされます。このエラーの後、ドライバーはドキュメントを挿入しません。

注意

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

const myDB = client.db("myDB");const myColl = myDB.collection("colors"); try { const docs = [ { "_id": 1, "color": "red"}, { "_id": 2, "color": "purple"}, { "_id": 1, "color": "yellow"}, { "_id": 3, "color": "blue"} ]; const insertManyresult = await myColl.insertMany(docs); let ids = insertManyresult.insertedIds; console.log(`${insertManyresult.insertedCount} documents were inserted.`); for (let id of Object.values(ids)) { console.log(`Inserted a document with id ${id}`); }} catch(e) { console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`); let ids = e.result.result.insertedIds; for (let id of Object.values(ids)) { console.log(`Processed a document with id ${id._id}`); } console.log(`Number of documents inserted: ${e.result.result.nInserted}`);}

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

A MongoBulkWriteException occurred, but there are successfully processed documents.Processed a document with id 1Processed a document with id 2Processed a document with id 1Processed a document with id 3Number of documents inserted: 2

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

{ "_id": 1, "color": "red" }{ "_id": 2, "color": "purple" }

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

次の例では、 insertMany()メソッドを使用して、3 つの新しいドキュメントをmyDB.pizzaMenuコレクションに挿入しています。

const myDB = client.db("myDB");const myColl = myDB.collection("pizzaMenu"); const docs = [ { name: "Sicilian pizza", shape: "square" }, { name: "New York pizza", shape: "round" }, { name: "Grandma pizza", shape: "square" }]; const insertManyresult = await myColl.insertMany(docs);let ids = insertManyresult.insertedIds; console.log(`${insertManyresult.insertedCount} documents were inserted.`); for (let id of Object.values(ids)) { console.log(`Inserted a document with id ${id}`);}

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

3 documents were inserted.Inserted a document with id 60ca09f4a40cf1d1afcd93a2Inserted a document with id 60ca09f4a40cf1d1afcd93a3Inserted a document with id 60ca09f4a40cf1d1afcd93a4

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

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoDB への接続」ガイドを参照してください。この例では、Atlas サンプル データセットに含まれる sample_mflix データベースの movies コレクションも使用します。MongoDB Get Startedに従って、MongoDB Atlasの無料クラスター上のデータベースに読み込むことができます。

次のコードは、多数の挿入操作を実行する完全なスタンドアロンファイルです。

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { // Get the database and collection on which to run the operation const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create an array of documents to insert const moviesToInsert = [ { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, ]; // Prevent additional documents from being inserted if one fails const options = { ordered: true }; // Execute insert operation const result = await movies.insertMany(moviesToInsert, options); // Print result console.log(`${result.insertedCount} documents were inserted`); } finally { await client.close(); }}run().catch(console.dir);

上記の例を実行すると、次の出力が生成されます。

3 documents were inserted

このガイドで説明した型やメソッドの詳細については、次の API ドキュメントを参照してください。