The insertMany method lets you add many records to a MongoDB collection at once. It saves time by inserting multiple items in one go instead of one by one.
0
0
insertMany method in MongoDB
Introduction
When you have a list of new users to add to your app's database.
When importing a batch of product details into an online store.
When saving multiple sensor readings collected at the same time.
When you want to quickly add several blog posts to a content database.
Syntax
MongoDB
db.collection.insertMany([document1, document2, ...], { options })The first argument is an array of documents (objects) to add.
The second argument is optional and can include settings like ordered to control behavior on errors.
Examples
Insert two user documents into the
users collection.MongoDB
db.users.insertMany([{ name: "Alice" }, { name: "Bob" }])Insert products and continue even if one insert fails.
MongoDB
db.products.insertMany([{ item: "Pen" }, { item: "Notebook" }], { ordered: false })Sample Program
This example switches to the shopDB database and inserts three product documents into the products collection.
MongoDB
use shopDB
db.products.insertMany([
{ name: "Chair", price: 25 },
{ name: "Table", price: 50 },
{ name: "Lamp", price: 15 }
])OutputSuccess
Important Notes
If one document fails to insert and ordered is true (default), MongoDB stops inserting the rest.
Each inserted document gets a unique _id if you don't provide one.
Summary
insertMany adds multiple documents to a collection in one call.
It is faster and easier than inserting documents one by one.
You can control error handling with options like ordered.