0
0
MongodbHow-ToBeginner · 3 min read

How to Bulk Insert Documents in MongoDB Quickly

To bulk insert documents in MongoDB, use the insertMany() method on a collection, passing an array of documents. This method inserts all documents in one operation, making it faster than inserting one by one.
📐

Syntax

The insertMany() method takes an array of documents to insert into a collection. It can also accept an optional options object.

  • collection.insertMany(arrayOfDocuments, options)
  • arrayOfDocuments: An array of JSON-like objects to insert.
  • options: Optional settings like ordered to control insert behavior.
mongodb
db.collection.insertMany([
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 }
], { ordered: true })
💻

Example

This example shows how to insert multiple user documents into a users collection using insertMany(). It inserts three users in one operation.

javascript
const { MongoClient } = require('mongodb');

async function run() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  try {
    await client.connect();
    const database = client.db('testdb');
    const users = database.collection('users');

    const docs = [
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 35 }
    ];

    const result = await users.insertMany(docs);
    console.log(`${result.insertedCount} documents were inserted.`);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
3 documents were inserted.
⚠️

Common Pitfalls

Common mistakes when bulk inserting include:

  • Passing a single document instead of an array to insertMany().
  • Not handling errors when ordered is true, which stops on first failure.
  • Inserting documents with duplicate _id fields causing errors.

Always ensure your data is an array and handle errors properly.

mongodb
/* Wrong: Passing single document */
db.collection.insertMany({ name: "Alice" });

/* Right: Pass an array */
db.collection.insertMany([{ name: "Alice" }]);
📊

Quick Reference

OptionDescription
arrayOfDocumentsArray of documents to insert
orderedBoolean; if true, stops on first error (default true)
writeConcernSpecifies the level of acknowledgment requested from MongoDB
bypassDocumentValidationIf true, skips document validation

Key Takeaways

Use insertMany() with an array of documents for bulk inserts in MongoDB.
Set the ordered option to control whether inserts stop on errors.
Always pass an array, not a single document, to insertMany().
Handle duplicate _id errors to avoid insert failures.
Bulk inserts are faster than inserting documents one by one.