MongoDB insertMany() Method: Insert Multiple Documents Using Shell & Node.js

MongoDB is a NoSQL database that can store a large amount of unstructured data. Data stored in MongoDB are easy to retrieve as it can hold them in flexible formats depending upon the need such as graphs, key values, documents, etc.

A MongoDB database has many collections in which we can insert records, the records in MongoDB are called documents. To insert documents into a MongoDB collection, two methods are mainly used: insertOne() and insertMany().

In this tutorial, we will see the process of inserting multiple documents into the MongoDB collection using MongoShell and Node.js by implementing the insertMany() method as insertOne() can only insert a single document at a time.

If you want to learn about the insertOne() function – MongoDB insertOne() Method: Inserting a Single Document into a Collection

MongoDB insertMany() Method

The insertMany() is the most basic function that we come across when using MongoDB. It allows us to insert one or more documents all together at a time. Moreover, you can even create a collection and add multiple documents using the insertMany() function. This function accepts an array of documents as an argument. 

Also, this function automatically adds the _id property for each document inserted so we do not need to specify it manually.

Syntax:

Let us take a quick look at the syntax to use insertMany() function in MongoDB.

db.collection.insertMany(
[document 1, document 2, …],
{
    writeConcern: document,
    ordered: boolean
})

Parameters:

  • collection is the name of the collection in which you want the documents to be inserted,
  • [document 1, document 2, …] is the array containing documents that will be inserted,
  • writeConcern is an optional parameter, it is used when you do not want to use the default write concern, and it allows you to control the acknowledgement behaviour for write operations (the majority of the time it is not required to pass this),
  • ordered is also an optional parameter, it takes a boolean value to specify where to follow the same order in which documents are passed.

Note:

As a default behaviour, this function will insert documents in the order we passed. You may set the ordered option as false if you do not want the function to follow the specified order.

Error Handling:

While attempting to use the insertMany() method, errors can be thrown due to various reasons like validation problems, duplicate field names, when key values are not unique, or any additional problems. To handle the error, you can use .then() and .catch() blocks since as a result insertMany() method returns a promise. For MongoDB shell, you can use try and catch blocks for error handling.

Let’s see how we can implement the above syntax to insert multiple documents using both Mongo Shell and Node.

Example of Inserting Multiple Documents in Mongo Shell

Mongo Shell is the fastest way of interacting with the MongoDB database, let’s see an example to demonstrate the use of this method in Mongo Shell.

Inserting documents using the insertMany() method in Mongo Shell:

1. Start up your MongoDB server.

2. Pick the database you want to use and navigate into it.

show dbs
use droneSpree

3. Take a look at all our existing documents in the chosen collection.

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1e"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Darkpact Y-copter X92",
        "price" : 79500,
        "weight" : "15 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1f"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Rizolli Debra TR-7",
        "price" : 48500,
        "weight" : "11 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe20"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Crohn Firebat O65",
        "price" : 12500,
        "weight" : "5 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}

Here we have used the find() method to fetch all documents and then used the pretty() method, if you want to know what it is, check out the tutorial: Pretty Print in MongoDB: What it is & How to Use it?

4. Now, let’s insert new documents into this collection using the insertMany() function.

> db.drones.insertMany([{
...         "utility" : [
...                 "Photography",
...                 "Combat",
...                 "Rescue",
...                 "Construction"
...         ],
...         "onSale" : false,
...         "name" : "Genevieve Portman’s Thunderfin",
...         "price" : 19500,
...         "weight" : "12 kilograms",
...         "additionalDetails" : {
...                 "material" : "lithium",
...                 "moreUses" : [
...                         "Videography",
...                         "Recreation"
...                 ]
...         }
... },
… {
...         "utility" : [
...                 "Photography",
...                 "Combat",
...                 "Rescue",
...                 "Construction"
...         ],
...         "onSale" : false,
...         "name" : "Berkeley Eagle 67",
...         "price" : 89500,
...         "weight" : "22 kilograms",
...         "additionalDetails" : {
...                 "material" : "glass fiber",
...                 "moreUses" : [
...                         "Videography",
...                         "Recreation"
...                 ]
...         }
... }
… ])

Here we have passed an array containing two documents in the insertMany function to insert it in a given collection.

Verifying if the documents have been inserted successfully:

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1e"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Darkpact Y-copter X92",
        "price" : 79500,
        "weight" : "15 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1f"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Rizolli Debra TR-7",
        "price" : 48500,
        "weight" : "11 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe20"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Crohn Firebat O65",
        "price" : 12500,
        "weight" : "5 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba1t76589"),
         "utility" : [
                 "Photography",
                 "Combat",
                 "Rescue",
                 "Construction"
         ],
         "onSale" : false,
         "name" : "Genevieve Portman’s Thunderfin",
         "price" : 19500,
         "weight" : "12 kilograms",
         "additionalDetails" : {
                 "material" : "lithium",
                 "moreUses" : [
                         "Videography",
                         "Recreation"
                 ]
         }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba178878"),
         "utility" : [
                 "Photography",
                 "Combat",
                 "Rescue",
                 "Construction"
         ],
         "onSale" : false,
         "name" : "Berkeley Eagle 67",
         "price" : 89500,
         "weight" : "22 kilograms",
         "additionalDetails" : {
                 "material" : "glass fiber",
                 "moreUses" : [
                         "Videography",
                         "Recreation"
                 ]
         }
}

See, we got the output containing all the documents, including those we just inserted. Also, you can notice that the insertMany() function automatically generated the ‘_id’ for newly inserted documents.

Example of Inserting Multiple Documents in Node.js

In the same manner, we can also use the MongoDB insertMany() function in a Node.js application. For this, you will need a Node.js application.

Inserting documents using the insertMany() method in Node.js:

1. Assume we have written the below code in a JavaScript file named insertManyDoc.js.

await db.drones.insertMany([{
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sloan Fray Flier 876",
        "price" : 8500,
        "weight" : "2 kilograms",
        "additionalDetails" : {
                "material" : "polystyrene",
                "moreUses" : [
                        "Land Inspection",
                        "Photography"
                ]
        }
},
{
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Trex3 Flier 003",
        "price" : 6700,
        "weight" : "5 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection",
                        "Videography"
                ]
        }
}
])

Just the above approach, here we have also provided the sample data we want to insert. We have used the await keyword for insert operations so that the program pauses the execution of the other block of code until the document gets inserted.

2. Locate the project folder in the terminal and execute the below command to install the MongoDB module.

npm i mongodb

3. Make sure that the MongoDB server is up and running and connected to your MongoDB instance.

4. Execute the below command to run the code of the “ insertManyDoc.js” file.

node insertManyDoc.js

Verifying if the documents have been inserted successfully:

Switch to Mongo Shell and print all the documents to see if the specified documents have been inserted or not.

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1e"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Darkpact Y-copter X92",
        "price" : 79500,
        "weight" : "15 kilograms",
        "additionalDetails" : {
                "material" : "glass fiber",
                "moreUses" : [
                        "Delivery",
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe1f"),
        "utility" : [
                "Videography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Rizolli Debra TR-7",
        "price" : 48500,
        "weight" : "11 kilograms",
        "additionalDetails" : {
                "material" : "carbon fiber",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba14cfe20"),
        "utility" : [
                "Photography",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Crohn Firebat O65",
        "price" : 12500,
        "weight" : "5 kilograms",
        "additionalDetails" : {
                "material" : "aluminum",
                "moreUses" : [
                        "Monitoring or Inspection",
                        "Recreation"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba1t76589"),
         "utility" : [
                 "Photography",
                 "Combat",
                 "Rescue",
                 "Construction"
         ],
         "onSale" : false,
         "name" : "Genevieve Portman’s Thunderfin",
         "price" : 19500,
         "weight" : "12 kilograms",
         "additionalDetails" : {
                 "material" : "lithium",
                 "moreUses" : [
                         "Videography",
                         "Recreation"
                 ]
         }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba178878"),
         "utility" : [
                 "Photography",
                 "Combat",
                 "Rescue",
                 "Construction"
         ],
         "onSale" : false,
         "name" : "Berkeley Eagle 67",
         "price" : 89500,
         "weight" : "22 kilograms",
         "additionalDetails" : {
                 "material" : "glass fiber",
                 "moreUses" : [
                         "Videography",
                         "Recreation"
                 ]
         }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba7432e"),
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Sloan Fray Flier 876",
        "price" : 8500,
        "weight" : "2 kilograms",
        "additionalDetails" : {
                "material" : "polystyrene",
                "moreUses" : [
                        "Land Inspection",
                        "Photography"
                ]
        }
}
{
        "_id" : ObjectId("6161c46c13ca7f1ba1654r3b"),
        "utility" : [
                "Security",
                "Combat",
                "Rescue",
                "Construction"
        ],
        "onSale" : false,
        "name" : "Trex3 Flier 003",
        "price" : 6700,
        "weight" : "5 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection",
                        "Videography"
                ]
        }
}

By looking at the above output, we can say that the insertion is successfully done.

Read More – Easy Guide to Use findOneAndUpdate in MongoDB Using Nodejs

Conclusion

In this article, we have learned to use the Insert Many function in the Mongo shell and Node.js. The insertMany() function is used to insert documents in MongoDB database collections, as the name suggests, it can insert multiple documents at one go. It takes an array as an argument containing many documents to be inserted into a given MongoDB database collection. We hope this article helps you to understand the insertMany() function in MongoDB. 

Want to update the code without restarting the Node server? Click here to read our guide on it.

Reference

https://www.mongodb.com/docs/manual/reference/method/db.collection.insertMany/

Aneesha S
Aneesha S
Articles: 172