Open In App

MongoDB insertMany() Method – db.Collection.insertMany()

The insertMany() method inserts one or more documents in the collection. It takes array of documents to insert in the collection. 

Syntax:



db.Collection_name.insertMany(
[<document 1>, <document 2>, ...],
{
    writeConcern: <document>,
    ordered: <boolean>
})

Parameters:

Optional Parameters:



Return Type:

This method returns :

Examples:

In the following examples, we are working with:

Database: gfg

Collection: student

Document: Empty

Example 1: Inserts the one document that contains the name and age of the student

db.student.insertMany([{name:"Akshay",age:18}])

Example 2: Insert the array of documents that contains the name and age of the students

db.student.insertMany([{name:"Ajay",age:20},
                       {name:"Bina",age:24},
                       {name:"Ram",age:23}])

Example 3: Insert multiple documents with _id field

db.student.insertMany([{_id:"stu200", name:"Ammu", age:18},
                       {_id:"stu201", name:"Priya", age:29}])

Example 4: Insert unordered documents by setting the value of ordered option to false

db.student.insertMany([{_id:"stu203",name:"Soniya",age:28}, 
                       {_id:"stu202", name:"Priya", age:25}], 
                       {ordered: false})

Article Tags :