Overview
通过本指南,您可以了解如何将文档插入 MongoDB。
您可以使用 MongoDB 来检索、更新和删除已存储在 MongoDB 中的信息。要存储信息,请使用插入操作。
插入操作会在 MongoDB 集合中插入一个或多个文档。Node.js 驱动程序提供了以下方法来执行插入操作:
insertOne()
insertMany()
bulkWrite()
提示
互动实验室
本页包括一个简短的交互式实验室,演示了如何使用 insertOne()
方法插入数据。无需安装 MongoDB 或代码编辑器,即可直接在浏览器窗口中完成此实验。
若要启动实验室,请单击页面顶部的“Open Interactive Tutorial”按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 (⛶)。
以下部分重点介绍insertOne()
和insertMany()
。有关如何使用bulkWrite()
方法的示例,请参阅批量操作指南的 bulkWrite() 示例:完整文件部分。
关于以下项的说明: _id
在插入文档时,MongoDB 默认为文档实施一个约束。每个文档必须 包含唯一的 _id
字段。
管理该字段有两种方法:
您可以自己管理该字段,确保使用的每个值都是唯一的。
您可以让驱动程序使用主键工厂自动生成唯一的
ObjectId
值。
除非您为唯一性提供了强有力的保证,否则我们建议让驱动程序自动生成 _id
值。
注意
重复的 _id
值违反了唯一索引约束,这会导致 WriteError
。
有关 _id
的更多信息,请参阅MongoDB Server手册中有关 唯一索引的条目。
插入单一文档
如果要插入单个文档,请使用 insertOne()
方法。
成功插入后,该方法将返回一个InsertOneResult
实例,该实例表示新文档的_id
。
例子
以下示例使用 insertOne()
方法在 myDB.pizzaMenu
集合中插入一个新文档:
const myDB = client.db("myDB"); const myColl = myDB.collection("pizzaMenu"); const doc = { name: "Neapolitan pizza", shape: "round" }; const result = await myColl.insertOne(doc); console.log( `A document was inserted with the _id: ${result.insertedId}`, );
输出类似于以下内容:
A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836
有关本节中提到的类和方法的更多信息,请参阅以下资源:
有关 InsertOneResult 的 API 文档
服务器手动条目 insertOne()
insertOne() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下代码是一个完整的独立运行文件,用于执行插入一个操作:
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 "sample_mflix" database and access its "movies" collection 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a document to insert 16 const doc = { 17 title: "Charade", 18 genres: ["Comedy", "Romance", "Thriller"], 19 year: 1963, 20 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], 21 } 22 // Insert the defined document into the "movies" collection 23 const result = await movies.insertOne(doc); 24 25 // Print the ID of the inserted document 26 console.log(`A document was inserted with the _id: ${result.insertedId}`); 27 } finally { 28 // Close the MongoDB client connection 29 await client.close(); 30 } 31 } 32 // Run the function and handle any errors 33 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 Movie { 9 title: string; 10 content: string[]; 11 year: number; 12 cast: string[]; 13 } 14 15 async function run() { 16 try { 17 const database = client.db("sample_mflix"); 18 // Specifying a Schema is optional, but it enables type hints on 19 // finds and inserts 20 const movies = database.collection<Movie>("movies"); 21 const result = await movies.insertOne({ 22 title: "Charade", 23 genres: ["Comedy", "Romance", "Thriller"], 24 year: 1963, 25 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], 26 }); 27 console.log(`A document was inserted with the _id: ${result.insertedId}`); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
运行上述示例将产生以下输出:
A document was inserted with the _id: ...
插入多个文档
如果要插入多份文档,请使用 insertMany()
方法。此方法将按指定的顺序插入文档,直到发生异常(如果有)。
例如,假设您要插入以下文档:
{ "_id": 1, "color": "red" } { "_id": 2, "color": "purple" } { "_id": 1, "color": "yellow" } { "_id": 3, "color": "blue" }
如果尝试插入这些文档,则在处理第三个文档时会发生 WriteError
,但错误之前的文档将插入到集合中。
注意
在错误发生之前,使用 try-catch 区块获取已成功处理文档的确认:
const myDB = client.db("myDB"); const myColl = myDB.collection("colors"); try { const docs = [ { "_id": 1, "color": "red"}, { "_id": 2, "color": "purple"}, { "_id": 1, "color": "yellow"}, { "_id": 3, "color": "blue"} ]; const insertManyresult = await myColl.insertMany(docs); let ids = insertManyresult.insertedIds; console.log(`${insertManyresult.insertedCount} documents were inserted.`); for (let id of Object.values(ids)) { console.log(`Inserted a document with id ${id}`); } } catch(e) { console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`); let ids = e.result.result.insertedIds; for (let id of Object.values(ids)) { console.log(`Processed a document with id ${id._id}`); } console.log(`Number of documents inserted: ${e.result.result.nInserted}`); }
输出包含 MongoDB 可以处理的文档,如下所示:
A MongoBulkWriteException occurred, but there are successfully processed documents. Processed a document with id 1 Processed a document with id 2 Processed a document with id 1 Processed a document with id 3 Number of documents inserted: 2
如果您查看集合,会看到以下文档:
{ "_id": 1, "color": "red" } { "_id": 2, "color": "purple" }
成功插入后,该方法会返回一个 InsertManyResult
实例,该实例表示已插入的文档的数量以及新文档的 _id
。
例子
以下示例使用 insertMany()
方法在 myDB.pizzaMenu
集合中插入三个新文档:
const myDB = client.db("myDB"); const myColl = myDB.collection("pizzaMenu"); const docs = [ { name: "Sicilian pizza", shape: "square" }, { name: "New York pizza", shape: "round" }, { name: "Grandma pizza", shape: "square" } ]; const insertManyresult = await myColl.insertMany(docs); let ids = insertManyresult.insertedIds; console.log(`${insertManyresult.insertedCount} documents were inserted.`); for (let id of Object.values(ids)) { console.log(`Inserted a document with id ${id}`); }
您的输出类似于以下内容:
3 documents were inserted. Inserted a document with id 60ca09f4a40cf1d1afcd93a2 Inserted a document with id 60ca09f4a40cf1d1afcd93a3 Inserted a document with id 60ca09f4a40cf1d1afcd93a4
有关本节中提到的类和方法的更多信息,请参阅以下资源:
有关 insertMany() 的 API 文档
关于 InsertManyResult 的 API 文档
PkFactory 上的 API 文档
关于insertMany()的服务器手册条目
insertMany() 示例:完整文件
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
以下代码是执行多次插入操作的完整独立运行文件:
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 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create an array of documents to insert 16 const moviesToInsert = [ 17 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, 18 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, 19 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, 20 ]; 21 22 // Prevent additional documents from being inserted if one fails 23 const options = { ordered: true }; 24 25 // Execute insert operation 26 const result = await movies.insertMany(moviesToInsert, options); 27 28 // Print result 29 console.log(`${result.insertedCount} documents were inserted`); 30 } finally { 31 await client.close(); 32 } 33 } 34 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 Movie { 9 title: string; 10 genres: string[]; 11 year: number; 12 cast: string[]; 13 } 14 15 async function run() { 16 try { 17 const database = client.db("sample_mflix"); 18 // Specifying a schema is optional, but it enables type hints on 19 // finds and inserts 20 const movies = database.collection<Movie>("movies"); 21 22 const result = await movies.insertMany( 23 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, 24 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, 25 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, 26 { ordered: true } 27 ); 28 console.log(`${result.insertedCount} documents were inserted`); 29 } finally { 30 await client.close(); 31 } 32 } 33 run().catch(console.dir);
运行上述示例将产生以下输出:
3 documents were inserted
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: