对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

插入文档

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

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

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

  • insertOne()

  • insertMany()

  • bulkWrite()

提示

互动实验室

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

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

以下部分重点介绍 insertOne() 和 insertMany()。有关如何使用bulkWrite() 方法的示例,请参阅批量操作指南的 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

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

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。

以下代码是一个完整的独立运行文件,用于执行插入一个操作:

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.const uri = "<connection string uri>"; // Create a new client and connect to MongoDBconst client = new MongoClient(uri); async function run() { try { // Connect to the "sample_mflix" database and access its "movies" collection const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a document to insert const doc = { title: "Charade", genres: ["Comedy", "Romance", "Thriller"], year: 1963, cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], } // Insert the defined document into the "movies" collection const result = await movies.insertOne(doc); // Print the ID of the inserted document console.log(`A document was inserted with the _id: ${result.insertedId}`); } finally { // Close the MongoDB client connection await client.close(); }}// Run the function and handle any errorsrun().catch(console.dir);

运行上述示例将产生以下输出:

A document was inserted with the _id: ...

如果要插入多份文档,请使用 insertMany() 方法。此方法将按指定的顺序插入文档,直到发生异常(如果有)。

例如,假设您要插入以下文档:

{ "_id": 1, "color": "red" }{ "_id": 2, "color": "purple" }{ "_id": 1, "color": "yellow" }{ "_id": 3, "color": "blue" }

当您将前面的文档传递给 insertMany() 方法时,驱动程序会插入第一个和第二个文档,但会为第三个文档抛出 WriteError,因为ID 1 重复。出现此错误后,驱动程序不会插入任何文档。

注意

在错误发生之前,使用 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 1Processed a document with id 2Processed a document with id 1Processed a document with id 3Number 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 60ca09f4a40cf1d1afcd93a2Inserted a document with id 60ca09f4a40cf1d1afcd93a3Inserted a document with id 60ca09f4a40cf1d1afcd93a4

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

注意

设置示例

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接到 MongoDB 指南。本示例还使用了Atlas 示例数据集中包含的 sample_mflix 数据库中的 movies 集合。您可以按照 MongoDB 入门指南,将它们加载到 MongoDB Atlas 的免费集群数据库中。

以下代码是执行多次插入操作的完整独立运行文件:

import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection string.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);

运行上述示例将产生以下输出:

3 documents were inserted

要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: