Open In App

MongoDB – Insert Multiple Document Using MongoShell

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by using db.collection.insertMany() method.

insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field. If you add documents without _id field, then mongodb will automatically add _id fields for each documents and assign them with a unique ObjectId. This method by default insert documents in order.

Syntax:

db.collection.insertMany(
   [  <Document1>, <Document2>, <Document3> ... ],
   {
      writeConcern: <Document>,
      order: <Boolean> 
   }
)

Parameters:

Document: It represents the array of the documents that will insert in the collection.
Optional Parameters:

  • writeConcern: It is only used when you do not want to use the default write concern,
  • order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true.

Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.

Examples:

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: student

Inserting multiple documents without _id field:

In this example, we are inserting multiple documents in the student collection without _id field using db.collection.insertMany() method.

Inserting multiple documents with field:

In this example, we are inserting multiple documents in the student collection with _id field using db.collection.insertMany() method.


Last Updated : 27 Feb, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads