The insertMany method in MongoDB is used to insert multiple documents into a collection in a single operation. This method is efficient for adding a batch of documents at once, reducing the number of round trips to the database compared to inserting documents one at a time.
Key Features of insertMany:
-
Batch Insertion: Allows you to insert an array of documents, making it faster than multiple individual insert operations.
-
Document Structure: Each document in the array can have a different structure, as MongoDB supports a flexible schema.
-
Acknowledgment: The method can return an acknowledgment of the operation, including the inserted document IDs.
-
Error Handling: If any document fails to insert due to validation errors or other issues, the entire operation can fail unless specified otherwise with options.
Syntax:
db.collection.insertMany(documents, options)
documents: An array of documents to be inserted.options: Optional settings, such asordered(to specify whether to stop on the first error) andwriteConcern(to specify the level of acknowledgment requested).
Example:
db.students.insertMany([
{ name: "Alice", age: 20 },
{ name: "Bob", age: 22 },
{ name: "Charlie", age: 23 }
])
In this example, three student documents are inserted into the students collection in one operation.
