Insert Multiple Documents

Info With Circle IconCreated with Sketch.Note

If you specify a callback method, insertMany() returns nothing. If you not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

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.

Info With Circle IconCreated with Sketch.Note

This example connects to an instance of MongoDB using a connection string. To learn more about connecting to your MongoDB instance, see the connection guide.

1const { MongoClient } = require("mongodb");
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
7const client = new MongoClient(uri);
9async function run() {
10 try {
11 await client.connect();
13 const database = client.db("sample_mflix");
14 const movies = database.collection("movies");
16 // create an array of documents to insert
17 const docs = [
18 { name: "Red", town: "Kanto" },
19 { name: "Blue", town: "Kanto" },
20 { name: "Leon", town: "Galar" }
21 ];
23 // this option prevents additional documents from being inserted if one fails
24 const options = { ordered: true };
26 const result = await movies.insertMany(docs, options);
27 console.log(`${result.insertedCount} documents were inserted`);
28 } finally {
29 await client.close();
30 }
Give Feedback