文档菜单
文档首页
/ / /
Node.js 驱动
/ / /

插入文档

本页内容

  • 概述
  • 关于的说明_id
  • 插入单个文档
  • 插入多个文档

在本指南中,您可以学习如何将文档插入到MongoDB中。

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

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

  • insertOne()

  • insertMany()

  • bulkWrite()

提示

交互式实验室

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

要开始实验室,请点击打开交互式教程按钮位于页面顶部。要全屏展开实验室,请点击实验室面板右上角的全屏按钮()。

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

当插入文档时,MongoDB 默认会对文档施加一个约束。每个文档都必须包含一个唯一的 _id 字段。

有两种方式来管理这个字段

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

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

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

注意

重复的 _id 值违反唯一索引约束,导致出现 WriteError

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

当您想插入单个文档时,请使用 insertOne() 方法。

在成功插入后,该方法返回一个代表新文档 _idInsertOneResult 实例。

以下示例使用 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

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

返回

写入