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.
- By default, documents are inserted in the given order if you want to insert documents in unordered, then set the value of ordered to false.
- Using this method you can also create a collection by inserting documents.
- You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error.
- This method can also throw a BulkWriteError exception.
- This method can also be used inside multi-document transactions.
Syntax:
db.Collection_name.insertMany(
[<document 1>, <document 2>, ...],
{
writeConcern: <document>,
ordered: <boolean>
})
Parameters:
- The first parameter is the array of documents to insert into the collection.
- The second parameter is optional.
Optional Parameters:
- writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
- ordered: The type of this parameter is boolean that specifies whether the MongoDB instance should perform an ordered or unordered insertion. If it is true insertion will be in ordered manner otherwise in unordered manner. Default it is true.
Return Type:
This method returns :
- Boolean acknowledged as true if write concern was enabled or false if write concern was disabled.
- The insertedId field with the _id value of the inserted document.
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})
Contact Us