insertMany()
insertMany adds several documents in one call, which is faster than many single inserts.
In this page:
Syntax
db.collection_name.insertMany([
{ field: value1 },
{ field: value2 }
], { ordered: false })
insertMany()
Pass an array of documents to insertMany. By default inserts are ordered and stop at the first error; pass { ordered: false } to continue past errors. The result lists the inserted ids by position. Batches also reduce network round trips.
Note:
ordered: false lets valid documents through even if one fails.
Example: insertMany()
test> db.products.insertMany([
... { _id: 1, name: "Pen", price: 3, stock: 100 },
... { _id: 2, name: "Notebook", price: 8, stock: 40 },
... { _id: 3, name: "Lamp", price: 45, stock: 5 }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.products.countDocuments()
3
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Passing separate arguments instead of one array
- Not using ordered false when partial success is fine
- Sending huge batches in one call
Chapter Summary
- insertMany takes an array
- Ordered inserts stop at the first error
- ordered: false continues
- Batching reduces round trips
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: