Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序
/ /

插入文档

您可以使用 collection.insertOne() 方法在集合中插入一个文档。要插入文档,请定义一个包含要存储的字段和值的对象。如果指定的集合不存在,则 insertOne() 方法会创建该集合。

您可以使用 options 参数指定更多查询选项。有关方法参数的更多信息,请参阅 insertOne() API 文档。有关此方法的更多信息,请参阅 insertOne() API 文档。

如果该操作成功插入文档,则会将 insertedId 字段附加到方法调用中传递的对象,并将该字段的值设置为插入文档的 _id

您可以使用 Node.js 驱动程序连接到以下环境中托管的部署并对其使用 insertOne() 方法:

  • MongoDB Atlas :用于在云中部署 MongoDB 的完全托管服务

  • MongoDB Enterprise:基于订阅、自行管理的 MongoDB 版本

  • MongoDB Community:source-available、免费使用且可自行管理的 MongoDB 版本

要了解有关在 MongoDB Atlas 托管部署的 Atlas 用户界面中插入文档的更多信息,请参阅创建、查看、更新和删除文档

注意

您可以使用此示例连接到 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>

后退

插入操作