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

複数のドキュメントの挿入

collection.insertMany() メソッドを使用して複数のドキュメントを挿入できます。insertMany() は、指定されたコレクションに挿入するドキュメントの配列を受け取ります。

insertMany() メソッドの 2 番目のパラメータとして渡される options オブジェクトで、さらにオプションを指定できます。配列内の前のドキュメントの挿入が失敗した場合に残りのドキュメントを挿入しないようにするには、ordered:true を指定します。

insertMany() 操作に誤ったパラメータを指定すると、問題が発生する可能性があります。ユニークインデックスのルールに違反する値を含むフィールドを挿入しようとすると、duplicate key error が返されます。

注意

この例を使用して、MongoDB のインスタンスに接続し、サンプルデータを含むデータベースと交流できます。MongoDB インスタンスへの接続とサンプルデータセットの読み込みの詳細については、 使用例ガイドを参照してください。

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("insertDB");
13 const foods = database.collection("foods");
14
15 // Create an array of documents to insert
16 const docs = [
17 { name: "cake", healthy: false },
18 { name: "lettuce", healthy: true },
19 { name: "donut", healthy: false }
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 foods.insertMany(docs, 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 Food {
9 name: string;
10 healthy: boolean;
11}
12
13async function run() {
14 try {
15 const database = client.db("insertDB");
16 // Specifying a schema is optional, but it enables type hints on
17 // finds and inserts
18 const foods = database.collection<Food>("foods");
19
20 const result = await foods.insertMany(
21 [
22 { name: "cake", healthy: false },
23 { name: "lettuce", healthy: true },
24 { name: "donut", healthy: false },
25 ],
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

戻る

ドキュメントの挿入