Docs Menu
Docs Home
/ / /
Node.js ドライバー
/

ドキュメントの挿入

このガイドでは、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コレクションも使用します。Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

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

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6// Create a new client and connect to MongoDB
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 // Connect to the "sample_mflix" database and access its "movies" collection
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create a document to insert
16 const doc = {
17 title: "Charade",
18 genres: ["Comedy", "Romance", "Thriller"],
19 year: 1963,
20 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"],
21 }
22 // Insert the defined document into the "movies" collection
23 const result = await movies.insertOne(doc);
24
25 // Print the ID of the inserted document
26 console.log(`A document was inserted with the _id: ${result.insertedId}`);
27 } finally {
28 // Close the MongoDB client connection
29 await client.close();
30 }
31}
32// Run the function and handle any errors
33run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10 content: string[];
11 year: number;
12 cast: string[];
13}
14
15async function run() {
16 try {
17 const database = client.db("sample_mflix");
18 // Specifying a Schema is optional, but it enables type hints on
19 // finds and inserts
20 const movies = database.collection<Movie>("movies");
21 const result = await movies.insertOne({
22 title: "Charade",
23 genres: ["Comedy", "Romance", "Thriller"],
24 year: 1963,
25 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"],
26 });
27 console.log(`A document was inserted with the _id: ${result.insertedId}`);
28 } finally {
29 await client.close();
30 }
31}
32run().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" }

これらのドキュメントを挿入しようとすると、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 1
Processed a document with id 2
Processed a document with id 1
Processed a document with id 3
Number 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 60ca09f4a40cf1d1afcd93a2
Inserted a document with id 60ca09f4a40cf1d1afcd93a3
Inserted a document with id 60ca09f4a40cf1d1afcd93a4

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

注意

セットアップ例

この例では、接続 URI を使用してMongoDBのインスタンスに接続します。MongoDBインスタンスへの接続の詳細については、 MongoDBへの接続 ガイドを参照してください。この例では、Atlasサンプルデータセットに含まれる sample_mflixデータベースの moviesコレクションも使用します。Atlas を使い始める」ガイドに従って、 MongoDB Atlasの無料階層のデータベースにロードできます。

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

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Create an array of documents to insert
16 const moviesToInsert = [
17 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
18 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
19 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
20 ];
21
22 // Prevent additional documents from being inserted if one fails
23 const options = { ordered: true };
24
25 // Execute insert operation
26 const result = await movies.insertMany(moviesToInsert, options);
27
28 // Print result
29 console.log(`${result.insertedCount} documents were inserted`);
30 } finally {
31 await client.close();
32 }
33}
34run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 title: string;
10 genres: string[];
11 year: number;
12 cast: string[];
13}
14
15async function run() {
16 try {
17 const database = client.db("sample_mflix");
18 // Specifying a schema is optional, but it enables type hints on
19 // finds and inserts
20 const movies = database.collection<Movie>("movies");
21
22 const result = await movies.insertMany(
23 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
24 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
25 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
26 { ordered: true }
27 );
28 console.log(`${result.insertedCount} documents were inserted`);
29 } finally {
30 await client.close();
31 }
32}
33run().catch(console.dir);

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

3 documents were inserted

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

戻る

CRUD 操作

項目一覧