0
0
MongodbComparisonBeginner · 3 min read

InsertOne vs insertMany in MongoDB: Key Differences and Usage

In MongoDB, insertOne inserts a single document into a collection, while insertMany inserts multiple documents at once. Use insertOne for single inserts and insertMany to efficiently add many documents in one operation.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of insertOne and insertMany in MongoDB.

FactorinsertOneinsertMany
Number of documents insertedOne documentMultiple documents (array)
Operation typeSingle insert operationBulk insert operation
Return valueResult with insertedIdResult with insertedIds object
PerformanceSlower for many insertsFaster for batch inserts
Error handlingError on single failureCan continue or stop on errors
Use caseInsert one recordInsert many records at once
⚖️

Key Differences

insertOne is designed to add exactly one document to a MongoDB collection. It returns a result containing the insertedId of the new document, making it easy to track that single insert. This method is simple and straightforward for cases where you only need to add one record.

On the other hand, insertMany accepts an array of documents and inserts them all in one operation. It returns an object with insertedIds, an object mapping indexes to the IDs for each inserted document. This bulk operation is more efficient when adding many documents because it reduces the number of round trips to the database.

Another difference is error handling: insertOne fails if the single insert fails, while insertMany can be configured with options like ordered to control whether it stops on the first error or continues inserting the rest.

⚖️

Code Comparison

Example of inserting a single document using insertOne:

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

async function runInsertOne() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('testdb');
  const collection = db.collection('users');

  const result = await collection.insertOne({ name: 'Alice', age: 25 });
  console.log('Inserted document ID:', result.insertedId);

  await client.close();
}

runInsertOne();
Output
Inserted document ID: ObjectId("some_generated_id")
↔️

insertMany Equivalent

Example of inserting multiple documents using insertMany:

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

async function runInsertMany() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('testdb');
  const collection = db.collection('users');

  const docs = [
    { name: 'Bob', age: 30 },
    { name: 'Carol', age: 27 },
    { name: 'Dave', age: 22 }
  ];

  const result = await collection.insertMany(docs);
  console.log('Inserted document IDs:', result.insertedIds);

  await client.close();
}

runInsertMany();
Output
Inserted document IDs: { '0': ObjectId("id1"), '1': ObjectId("id2"), '2': ObjectId("id3") }
🎯

When to Use Which

Choose insertOne when you need to add a single document and want simple, direct insertion with immediate feedback on that one record. It is ideal for operations like adding a new user or logging a single event.

Choose insertMany when you have multiple documents to add at once, such as importing data or batch processing. It is more efficient and faster because it reduces the number of database calls and can handle errors flexibly.

Key Takeaways

Use insertOne for inserting a single document with simple feedback.
Use insertMany to insert multiple documents efficiently in one operation.
insertMany returns an object of inserted IDs, while insertOne returns a single inserted ID.
insertMany can be configured to continue inserting even if some documents fail.
Choosing the right method improves performance and error handling in your MongoDB operations.