Insert Multiple Documents
You can insert multiple documents using the
collection.insertMany() method. The insertMany()
takes an array
of documents to insert into the specified collection.
You can specify additional options in the options
object passed as the
second parameter of the insertMany()
method. Specify ordered:true
to prevent inserting the remaining documents if the insertion failed for a
previous document in the array.
Specifying incorrect parameters for your insertMany()
operation can
cause problems. Attempting to insert a field to a value that would violate
unique index rules will throw a duplicate key error
.
Example
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async 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 } 34 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Food { 9 name: string; 10 healthy: boolean; 11 } 12 13 async 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 } 33 run().catch(console.dir);
If you run the preceding example, you should see the following output:
3 documents were inserted