Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序
/ /

插入多个文档

您可以使用 collection.insertMany() 方法插入多个文档。insertMany() 会将一组文档插入到指定集合中。

您可以使用作为 options 方法的第二个参数传递的 insertMany() 对象指定更多选项。指定 ordered:true 以防止在数组中的上一文档插入失败时插入剩余文档。

insertMany() 操作指定不正确的参数可能会导致问题。尝试插入值违反唯一索引规则的字段会导致 duplicate key error

注意

您可以使用此示例连接到 MongoDB 实例,并与包含样本数据的数据库进行交互。要了解有关连接到 MongoDB 实例和加载样本数据集的更多信息,请参阅使用示例指南。

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("insertDB");
13 const foods = database.collection("foods");
14
15 // Create an array of documents to insert
16 const docs = [
17 { name: "cake", healthy: false },
18 { name: "lettuce", healthy: true },
19 { name: "donut", healthy: false }
20 ];
21
22 // Prevent additional documents from being inserted if one fails
23 const options = { ordered: true };
24
25 // Execute insert operation
26 const result = await foods.insertMany(docs, options);
27
28 // Print result
29 console.log(`${result.insertedCount} documents were inserted`);
30 } finally {
31 await client.close();
32 }
33}
34run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Food {
9 name: string;
10 healthy: boolean;
11}
12
13async function run() {
14 try {
15 const database = client.db("insertDB");
16 // Specifying a schema is optional, but it enables type hints on
17 // finds and inserts
18 const foods = database.collection<Food>("foods");
19
20 const result = await foods.insertMany(
21 [
22 { name: "cake", healthy: false },
23 { name: "lettuce", healthy: true },
24 { name: "donut", healthy: false },
25 ],
26 { ordered: true }
27 );
28 console.log(`${result.insertedCount} documents were inserted`);
29 } finally {
30 await client.close();
31 }
32}
33run().catch(console.dir);

运行前面的示例,您将看到以下输出:

3 documents were inserted

后退

插入文档