← Back to MongoDB Course | Chapter 2: CRUD — Create | Lesson 7 of 7

Bulk insert

For big loads, insert in batches or use bulkWrite to send many operations together.

In this page:

  1. Bulk insert
Syntax
javascript
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

bash
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
  1. One insert per document in a loop
  2. Sending a single enormous batch
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.