Insert Multiple Documents插入多个文档
You can insert multiple documents using the collection.insertMany()您可以使用 method.
collection.insertMany()
方法插入多个文档。
The insertMany()
takes an array of documents to insert into the specified collection.insertMany()
获取要插入到指定集合中的文档数组。
You can specify additional options in the 您可以在作为options
object passed as the second parameter of the insertMany()
method. insertMany()
方法的第二个参数传递的options
对象中指定其他选项。Specify 指定ordered:true
to prevent inserting the remaining documents if the insertion failed for a previous document in the array.ordered: true
可在数组中前一个文档的插入失败时阻止插入其余文档。
Specifying incorrect parameters for your 为insertMany()
operation can cause problems. insertMany()
操作指定不正确的参数可能会导致问题。Attempting to insert a field to a value that would violate unique index rules will throw a 试图向违反唯一索引规则的值插入字段将引发duplicate key error
.duplicate key error
。
Example实例
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB的实例,并与包含示例数据的数据库进行交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例和加载示例数据集的更多信息,请参阅用法实例指南。
import { MongoClient } from "mongodb";
//Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const uri = "<connection string uri>";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("insertDB");
const foods = database.collection("foods");
//create an array of documents to insert创建要插入的文档数组
const docs = [
{ name: "cake", healthy: false },
{ name: "lettuce", healthy: true },
{ name: "donut", healthy: false }
];
//this option prevents additional documents from being inserted if one fails如果一个文档插入失败,该选项将阻止插入其他文档
const options = { ordered: true };
const result = await foods.insertMany(docs, options);
console.log(`${result.insertedCount} documents were inserted`);
} finally {
await client.close();
}
}
run().catch(console.dir);
If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:
3 documents were inserted