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
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10 const database = client.db("insertDB");
11 const haiku = database.collection("haiku");
12 // create a document to insert
13 const doc = {
14 title: "Record of a Shriveled Datum",
15 content: "No bytes, no problem. Just insert a document, in MongoDB",
16 }
17 const result = await haiku.insertOne(doc);
18
19 console.log(`A document was inserted with the _id: ${result.insertedId}`);
20 } finally {
21 await client.close();
22 }
23}
24run().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>

后退

插入操作