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

ドキュメントの挿入

collection.insertOne() メソッドを使用してコレクションにドキュメントを挿入できます使用して複数のドキュメントを挿入できます。 ドキュメントを挿入するには、保存するフィールドと値を含む オブジェクトを定義します。 指定されたコレクションが存在しない場合は、 insertOne()メソッドによってコレクションが作成されます。

options パラメーターを使用して、さらにクエリ オプションを指定できます。メソッド パラメーターの詳細については、insertOne() API ドキュメントを参照してください。このメソッドの詳細については、insertOne() API ドキュメントを参照してください。

この操作でドキュメントが正常に挿入されると、メソッド呼び出しで渡されたオブジェクトに insertedId フィールドが追加され、フィールドの値が挿入されたドキュメントの _id に設定されます。

Node.js ドライバーを使用して接続し、次の環境でホストされているデプロイメントにinsertOne()メソッドを使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる、MongoDB の自己管理型バージョン

MongoDB Atlas でホストされている配置の Atlas UI にドキュメントを挿入する方法の詳細については、「 ドキュメントの作成、表示、更新、および削除 」を参照してください。

注意

この例を使用して、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
6// Create a new client and connect to MongoDB
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 // Connect to the "insertDB" database and access its "haiku" collection
12 const database = client.db("insertDB");
13 const haiku = database.collection("haiku");
14
15 // Create a document to insert
16 const doc = {
17 title: "Record of a Shriveled Datum",
18 content: "No bytes, no problem. Just insert a document, in MongoDB",
19 }
20 // Insert the defined document into the "haiku" collection
21 const result = await haiku.insertOne(doc);
22
23 // Print the ID of the inserted document
24 console.log(`A document was inserted with the _id: ${result.insertedId}`);
25 } finally {
26 // Close the MongoDB client connection
27 await client.close();
28 }
29}
30// Run the function and handle any errors
31run().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 Haiku {
9 title: string;
10 content: string;
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 haiku = database.collection<Haiku>("haiku");
19 const result = await haiku.insertOne({
20 title: "Record of a Shriveled Datum",
21 content: "No bytes, no problem. Just insert a document, in MongoDB",
22 });
23 console.log(`A document was inserted with the _id: ${result.insertedId}`);
24 } finally {
25 await client.close();
26 }
27}
28run().catch(console.dir);

前の例を実行すると、次の出力が表示されます。

A document was inserted with the _id: <your _id value>

戻る

挿入操作