How to Use insertMany in MongoDB: Syntax and Examples
Use
insertMany() in MongoDB to add multiple documents to a collection at once by passing an array of objects. It returns a result object with details about the inserted documents.Syntax
The insertMany() method takes an array of documents to insert and an optional options object.
- documents: An array of objects representing the documents to insert.
- options (optional): Settings like
orderedto control if insertion stops on error.
It returns a promise that resolves with an object containing the inserted IDs.
javascript
db.collection.insertMany(documents, options)
Example
This example shows how to insert three user documents into a users collection using insertMany(). It logs the inserted IDs on success.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); const result = await users.insertMany([ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ]); console.log('Inserted IDs:', result.insertedIds); } finally { await client.close(); } } run().catch(console.dir);
Output
Inserted IDs: { '0': ObjectId('...'), '1': ObjectId('...'), '2': ObjectId('...') }
Common Pitfalls
Common mistakes when using insertMany() include:
- Passing a single object instead of an array, which causes an error.
- Not handling errors when
orderedis true, causing the operation to stop on first failure. - Ignoring the returned
insertedIdswhich helps track inserted documents.
Always pass an array and consider using { ordered: false } to continue inserting even if some documents fail.
javascript
/* Wrong: Passing single object */ db.collection.insertMany({ name: 'Alice' }); // Error /* Right: Passing array */ db.collection.insertMany([{ name: 'Alice' }]); /* Using ordered option */ db.collection.insertMany( [{ _id: 1 }, { _id: 1 }], { ordered: false } ); // Continues inserting despite duplicate key error on second document
Quick Reference
Here is a quick summary of insertMany() usage:
| Parameter | Description | Example |
|---|---|---|
| documents | Array of documents to insert | [{ name: 'A' }, { name: 'B' }] |
| options | Optional settings like ordered | { ordered: false } |
| returns | Promise with insertedIds | { insertedIds: { '0': ObjectId, '1': ObjectId } } |
Key Takeaways
Use insertMany() to insert multiple documents by passing an array.
Always pass an array, not a single object, to insertMany().
Use the ordered option to control error handling during insertion.
Check the insertedIds in the result to confirm inserted documents.
Handle errors properly to avoid partial insert failures.