Bulk insert
For big loads, insert in batches or use bulkWrite to send many operations together.
In this page:
Syntax
db.collection_name.insertMany(documents, { ordered: false })
db.collection_name.bulkWrite([
{ insertOne: { document: doc } },
{ deleteOne: { filter: filter } }
])
Bulk insert
insertMany with ordered: false is the simplest bulk insert. bulkWrite mixes inserts, updates and deletes in one round trip and reports counts for each type. For millions of documents use mongoimport or batches of a few thousand.
Note:
Batches of 1,000 to 10,000 documents are a good starting point.
Example: Bulk insert
test> const docs = [];
test> for (let i = 1; i <= 5; i++) docs.push({ _id: i, n: i, square: i * i });
test> db.squares.insertMany(docs)
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
}
test> db.squares.find({ square: { $gte: 9 } }, { _id: 0 })
[ { n: 3, square: 9 }, { n: 4, square: 16 }, { n: 5, square: 25 } ]
test> db.squares.countDocuments()
5
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- One insert per document in a loop
- Sending a single enormous batch
- Ignoring the per-operation results
Chapter Summary
- insertMany with ordered false
- bulkWrite mixes operation types
- Batch sizes of thousands
- mongoimport loads files
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: