Insert a Document插入文件¶
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.您可以让驱动程序自动生成唯一的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 creates and inserts a document using the 以下示例使用insertOne()
method:insertOne()
方法创建和插入文档:
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await collection.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块获取已成功处理文档的确认:
try {
const docs = [
{ "_id": 1, "color": "red"},
{ "_id": 2, "color": "purple"},
{ "_id": 1, "color": "yellow"},
{ "_id": 3, "color": "blue"}
];
const insertManyresult = await collection.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 creates and adds three documents using the 以下示例使用insertMany()
method:insertMany()
方法创建并添加三个文档:
const docs = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" }
];
const insertManyresult = await collection.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
- Server Manual Entry on insertMany()
- Runnable Insert Multiple Documents Example