插入文档
您可以使用以下方式将文档插入到集合中:collection.insertOne() 方法。要插入一个文档,定义一个包含要存储的字段和值的对象。如果指定的集合不存在,则insertOne()
方法将创建该集合。
您可以使用 options
参数指定更多查询选项。有关方法参数的更多信息,请参阅insertOne() API 文档。有关此方法的更多信息,请参阅insertOne() API 文档。
如果操作成功插入文档,它将在方法调用传入的对象中追加一个 insertedId
字段,并将字段的值设置为插入文档的 _id
。
兼容性
您可以使用 Node.js 驱动程序进行连接和使用 insertOne()
方法以下环境中的部署
MongoDB Atlas:云中 MongoDB 部署的全托管服务
MongoDB 企业版:基于订阅、自行管理的 MongoDB 版本
MongoDB 社区版:开源、免费使用、自行管理的 MongoDB 版本
了解更多关于在 Atlas UI 中插入文档的信息对于托管在 MongoDB Atlas 中的部署,请参阅 创建、查看、更新和删除文档。
示例
注意
您可以使用此示例连接到 MongoDB 实例并与包含样本数据的数据库交互。要了解更多关于连接到您的 MongoDB 实例和加载样本数据集的信息,请参阅使用示例指南.
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 // Create a new client and connect to MongoDB 7 const client = new MongoClient(uri); 8 9 async 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 31 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Haiku { 9 title: string; 10 content: string; 11 } 12 13 async 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 } 28 run().catch(console.dir);
运行前面的示例,您将看到以下输出
A document was inserted with the _id: <your _id value>