Insert a Document插入文档
On this page本页内容
Overview概述
In this guide, you can learn how to insert documents into MongoDB.在本指南中,您可以学习如何将文档插入MongoDB。
You can use MongoDB to retrieve, update and delete information. 您可以使用MongoDB来检索、更新和删除信息。To perform any of those operations, that information, such as user profiles and orders, needs to exist in MongoDB. 要执行任何这些操作,这些信息(如用户配置文件和订单)都需要存在于MongoDB中。For that information to exist, you need to first perform an insert operation.要使该信息存在,您需要首先执行插入操作。
An insert operation inserts a single or multiple documents in MongoDB using the 插入操作使用insertOne()
, insertMany()
and bulkWrite()
methods.insertOne()
、insertMany()
和bulkWrite()
方法在MongoDB中插入单个或多个文档。
The following sections focus on 以下部分主要介绍insertOne()
and insertMany()
. insertOne()
和insertMany()
。For an example on how to use the 有关如何使用bulkWrite()
method, see our runnable Bulk Operations Example.bulkWrite()
方法的示例,请参阅可运行批量操作示例。
A Note About _id
关于_id
的注意事项
_id
When inserting a document, MongoDB enforces one constraint on your documents by default. 在插入文档时,MongoDB默认情况下会对文档强制执行一个约束。Each document must contain a unique 每个文档必须包含一个唯一的_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您可以让驱动程序使用主键工厂自动生成唯一的ObjectId
values 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
值。
Duplicate 重复的_id
values violate unique index constraints, resulting in a WriteError
._id
值违反了唯一索引约束,导致WriteError
。
For additional 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: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}`,
);
Your output should look something like this:您的输出应该如下所示:
A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836
For additional information on the classes and methods mentioned in this section, see the following resources:有关本节中提到的类和方法的其他信息,请参阅以下资源:
API Documentation oninsertOne()
的API文档
API Documentation onInsertOneResult
的API文档
Server Manual Entry oninsertOne()
的服务器手册Runnable可运行Insert a Document Example插入文档示例
Insert Multiple Documents插入多个文档
Use the 如果要插入多个文档,请使用insertMany()
method when you want to insert multiple documents. insertMany()
方法。This method inserts documents in the order specified until an exception occurs, if any.此方法按指定的顺序插入文档,直到出现异常(如果有的话)。
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 at the third document and the documents prior to the error get inserted into your collection.WriteError
,并且错误之前的文档会插入到您的集合中。
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 should look something like this:输出由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 should look something like this:您的输出应该如下所示:
3 documents were inserted.
Inserted a document with id 60ca09f4a40cf1d1afcd93a2
Inserted a document with id 60ca09f4a40cf1d1afcd93a3
Inserted a document with id 60ca09f4a40cf1d1afcd93a4
For additional information on the classes and methods mentioned in this section, see the following resources:有关本节中提到的类和方法的其他信息,请参阅以下资源:
- API Documentation on
insertMany()
- API Documentation on
InsertManyResult
- API Documentation on
PkFactory
- Server Manual Entry on
insertMany()
- Runnable
Insert Multiple Documents Example插入多个文档示例