MongoDB – Insert Multiple Document Using MongoShell

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.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.