Overview概述
In this guide, you can learn how to insert documents into MongoDB.在本指南中,您可以学习如何将文档插入MongoDB。
You can use MongoDB to retrieve, update, and delete information that is already stored in MongoDB. To store information, use an insert operation.您可以使用MongoDB来检索、更新和删除已经存储在MongoDB中的信息。要存储信息,请使用插入操作。
An insert operation inserts one or more documents into a MongoDB collection. The Node.js driver provides the following methods to perform insert operations:插入操作将一个或多个文档插入到MongoDB集合中。Node.js驱动程序提供以下方法来执行插入操作:
insertOne()insertMany()bulkWrite()
Tip
Interactive Lab互动实验室
This page includes a short interactive lab that demonstrates how to insert data by using the 此页面包括一个简短的交互式实验室,演示如何使用insertOne() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.insertOne()方法插入数据。您可以直接在浏览器窗口中完成此实验,而无需安装MongoDB或代码编辑器。
To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.要启动实验室,请单击页面顶部的“打开交互式教程”按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮(⛶)。
The following sections focus on 以下部分重点介绍insertOne() and insertMany(). For an example on how to use the bulkWrite() method, see the bulkWrite() Example: Full File section of the Bulk Operations guide.insertOne()和insertMany()。有关如何使用bulkWrite()方法的示例,请参阅《批量操作》指南的bulkWriter()示例:完整文件部分。
A Note About _id关于_id的说明
_idWhen inserting a document, MongoDB enforces one constraint on your documents by default. Each document must contain a unique 插入文档时,MongoDB默认对文档强制执行一个约束。每个文档必须包含一个唯一的_id field._id字段。
There are two ways to manage this field:有两种方法可以管理此字段:
You can manage this field yourself, ensuring each value you use is unique.您可以自己管理此字段,确保您使用的每个值都是唯一的。You can let the driver automatically generate unique您可以让驱动程序使用主键工厂自动生成唯一的ObjectIdvalues with the primary key factory.ObjectId值。
Unless you have provided strong guarantees for uniqueness, we recommend you let the driver automatically generate 除非您为唯一性提供了强有力的保证,否则我们建议您让驱动程序自动生成_id values._id值。
Note
Duplicate 重复的_id values violate unique index constraints, resulting in a WriteError._id值违反了唯一索引约束,导致WriteError。
For more information about 有关_id, see the Server manual entry on Unique Indexes._id的更多信息,请参阅服务器手册中关于唯一索引的条目。
Insert a Single Document插入单个文档
Use the 当您想插入单个文档时,请使用insertOne() method when you want to insert a single document.insertOne()方法。
On successful insertion, the method returns an 成功插入后,该方法返回一个InsertOneResult instance representing the _id of the new document.InsertOneResult实例,表示新文档的_id。
Example示例
The following example uses the 以下示例使用insertOne() method to insert a new document into the myDB.pizzaMenu collection:myDB.pizzaMenu方法将新文档插入到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}`,
);
Your output looks similar to the following text:您的输出类似于以下文本:
A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836
For more information on the classes and methods mentioned in this section, see the following resources:有关本节中提到的类和方法的更多信息,请参阅以下资源:
API Documentation on insertOne()关于insertOne()的API文档API Documentation on InsertOneResult关于InsertOneResult的API文档Server manual entry on insertOne()insertOne()上的服务器手册输入
insertOne() Example: Full FileinsertOne()示例:完整文件
Note
Example Setup示例设置
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
The following code is a complete, standalone file that performs an insert one operation:以下代码是一个完整的独立文件,用于执行插入操作:
JavaScript
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 {
// Get the database and collection on which to run the operation获取要在其上运行操作的数据库和集合
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create an array of documents to insert创建要插入的文档数组
const moviesToInsert = [
{ title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
{ title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
{ title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
];
// Prevent additional documents from being inserted if one fails如果一个文档失败,则阻止插入其他文档
const options = { ordered: true };
// Execute insert operation执行插入操作
const result = await movies.insertMany(moviesToInsert, options);
// Print result打印结果
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
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);
interface Movie {
title: string;
genres: string[];
year: number;
cast: string[];
}
async function run() {
try {
const database = client.db("sample_mflix");
// Specifying a schema is optional, but it enables type hints on finds and inserts指定架构是可选的,但它可以在查找和插入时启用类型提示
const movies = database.collection<Movie>("movies");
const result = await movies.insertMany(
{ title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
{ title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
{ title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
{ ordered: true }
);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);Running the preceding example results in the following output:运行前面的示例会得到以下输出:
A document was inserted with the _id: ...Insert Multiple Documents插入多个文档
Use the 当您想插入多个文档时,请使用insertMany() method when you want to insert multiple documents. This method inserts documents in the order specified until an exception occurs, if any.insertMany()方法。此方法按照指定的顺序插入文档,直到出现异常(如果有的话)。
For example, assume you want to insert the following documents:例如,假设您想插入以下文档:
{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }
{ "_id": 1, "color": "yellow" }
{ "_id": 3, "color": "blue" }
If you attempt to insert these documents, a 如果尝试插入这些文档,则在处理第三个文档时会发生WriteError occurs when the third document is processed, but the documents before the error are inserted into your collection.WriteError,但错误之前的文档会插入到您的集合中。
Note
Use a try-catch block to get an acknowledgment for successfully processed documents before the error occurs:在错误发生之前,使用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}`);
}
The output consists of documents MongoDB can process and looks similar to the following:输出由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
If you look inside your collection, you see the following documents:如果你查看你的集合,你会看到以下文件:
{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }On successful insertion, the method returns an 成功插入后,该方法返回一个InsertManyResult instance representing the number of documents inserted and the _id of the new document.InsertManyResult实例,表示插入的文档数量和新文档的_id。
Example示例
The following example uses the 以下示例使用insertMany() method to insert three new documents into the myDB.pizzaMenu collection: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}`);
}
Your output looks similar to the following:您的输出类似于以下内容:
3 documents were inserted.
Inserted a document with id 60ca09f4a40cf1d1afcd93a2
Inserted a document with id 60ca09f4a40cf1d1afcd93a3
Inserted a document with id 60ca09f4a40cf1d1afcd93a4
For more information on the classes and methods mentioned in this section, see the following resources:有关本节中提到的类和方法的更多信息,请参阅以下资源:
API Documentation on insertMany()关于insertMany()的API文档API Documentation on InsertManyResult关于InsertManyResult的API文档API Documentation on PkFactory关于PkFactory的API文档Server manual entry on insertMany()insertMany()时的服务器手册输入
insertMany() Example: Full FileinsertMany()示例:完整文件
Note
Example Setup示例设置
This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the 此示例还使用Atlas示例数据集中包含的movies collection in the sample_mflix database included in the Atlas sample datasets. sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。
The following code is a complete, standalone file that performs an insert many operation:以下代码是一个完整的独立文件,用于执行插入多个操作:
JavaScript
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 {
// Get the database and collection on which to run the operation获取要在其上运行操作的数据库和集合
const database = client.db("sample_mflix");
const movies = database.collection("movies");
// Create an array of documents to insert创建要插入的文档数组
const moviesToInsert = [
{ title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
{ title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
{ title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
];
// Prevent additional documents from being inserted if one fails如果一个文档失败,则阻止插入其他文档
const options = { ordered: true };
// Execute insert operation执行插入操作
const result = await movies.insertMany(moviesToInsert, options);
// Print result打印结果
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);TypeScript
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);
interface Movie {
title: string;
genres: string[];
year: number;
cast: string[];
}
async function run() {
try {
const database = client.db("sample_mflix");
// Specifying a schema is optional, but it enables type hints on finds and inserts指定架构是可选的,但它可以在查找和插入时启用类型提示
const movies = database.collection<Movie>("movies");
const result = await movies.insertMany(
{ title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] },
{ title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] },
{ title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] },
{ ordered: true }
);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);Running the preceding example results in the following output:运行前面的示例会得到以下输出:
3 documents were insertedAPI Documentation文档
To learn more about any of the types or methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: