Docs HomeNode.js

Insert a Document插入一个文档

You can insert a document into a collection using the collection.insertOne() method. 您可以使用collection.insertOne()方法将文档插入集合中。To insert a document, define an object that contains the fields and values that you want to store. 若要插入文档,请定义一个包含要存储的字段和值的对象。If the specified collection does not exist, the insertOne() method creates the collection.如果指定的集合不存在,insertOne()方法将创建该集合。

You can specify additional query options using the options parameter. 可以使用options参数指定其他查询选项。For more information on the method parameters, see the insertOne() API documentation. 有关方法参数的更多信息,请参阅insertOne()API文档For more information on this method, see the insertOne() API documentation.有关此方法的更多信息,请参阅insertOne()API文档

If the operation successfully inserts a document, it appends an insertedId field to the object passed in the method call, and sets the value of the field to the _id of the inserted document.如果操作成功插入文档,它会将insertedId字段附加到方法调用中传递的对象,并将该字段的值设置为插入文档的_id

Example实例

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB的实例,并与包含示例数据的数据库进行交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例和加载示例数据集的更多信息,请参阅用法示例指南

import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const uri = "<connection string uri>";

const client = new MongoClient(uri);

async function run() {
try {
const database = client.db("insertDB");
const haiku = database.collection("haiku");
// create a document to insert创建要插入的文档
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc);

console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);

If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:

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