Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Node.js 驱动程序

插入文档

在此页面上

  • 概述
  • 关于以下项的说明: _id
  • 插入单一文档
  • 插入多个文档

通过本指南,您可以了解如何将文档插入 MongoDB。

您可以使用 MongoDB 检索、更新和删除已存储在 MongoDB 中的信息。要存储信息,请使用插入操作

插入操作会在 MongoDB 集合中插入一个或多个文档。Node.js 驱动程序提供了以下方法来执行插入操作:

  • insertOne()

  • insertMany()

  • bulkWrite()

提示

互动实验室

本页包括一个简短的交互式实验,演示如何使用insertOne()方法插入数据。您可以直接在浏览器窗口中完成此实验,而无需安装 MongoDB 或代码编辑器。

要开始实验,请单击页面顶部的 Open Interactive Tutorial按钮。要将实验室扩展为全屏格式,请单击实验室窗格右上角的全屏按钮 ( )。

以下各部分重点介绍 insertOne()insertMany()。有关如何使用 bulkWrite() 方法的示例,请参阅我们可运行的批量操作示例

在插入文档时,MongoDB 默认为文档实施一个约束。每个文档必须 包含唯一的 _id 字段。

管理该字段有两种方法:

  • 您可以自己管理该字段,确保使用的每个值都是唯一的。

  • 您可以让驱动程序使用主键工厂自动生成唯一的 ObjectId 值。

除非您为唯一性提供了强有力的保证,否则我们建议让驱动程序自动生成 _id 值。

注意

重复的 _id 值违反了唯一索引约束,这会导致 WriteError

有关_id的更多信息,请参阅服务器手册中有关 唯一索引的条目。

如果要插入单个文档,请使用 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

有关本节中提到的类和方法的更多信息,请参阅以下资源:

如果要插入多份文档,请使用 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

有关本节中提到的类和方法的更多信息,请参阅以下资源:

← 写入操作