Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Insert Multiple Documents

Note

If you specify a callback method, insertMany() returns nothing. If you do 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.

Note

This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples guide.

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