Lesson

MongoDB Insert

10 min reading
Free Course

MongoDB Insert in Node.js: insertOne() and insertMany()

Inserting records into a MongoDB collection in Node.js uses collection.insertOne() for a single document and collection.insertMany() for batches. If a document omits _id, the MongoDB Node.js driver generates a unique ObjectId automatically and returns insertedId (or insertedIds) so you can link related data right away.

Inserting Single Documents and Bulk Batches

Always attach timestamps (createdAt: new Date()) explicitly in Node.js and handle duplicate-key errors (err.code === 11000) when inserting into collections with unique indexes.

import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017');

async function seedProducts() {
  try {
    await client.connect();
    const products = client.db('kodersolution_store').collection('products');

    const single = await products.insertOne({
      sku: 'KB-101',
      name: 'Wireless Mechanical Keyboard',
      price: 89.99,
      tags: ['peripherals', 'keyboard'],
      createdAt: new Date(),
    });
    console.log('Inserted ID:', single.insertedId);

    const batch = await products.insertMany(
      [
        { sku: 'MS-202', name: 'Ergonomic Mouse', price: 49.0, createdAt: new Date() },
        { sku: 'HB-303', name: 'USB-C Hub', price: 34.5, createdAt: new Date() },
      ],
      { ordered: false }
    );
    console.log('Batch inserted count:', batch.insertedCount);
  } catch (err) {
    if (err.code === 11000) {
      console.error('Duplicate SKU skipped or rejected.');
    } else {
      throw err;
    }
  } finally {
    await client.close();
  }
}

seedProducts().catch(console.error);

Understanding { ordered: true } vs { ordered: false }

By default, insertMany() runs with { ordered: true }, stopping immediately at the first error and skipping remaining documents in the array. Passing { ordered: false } tells MongoDB to continue inserting all other valid documents even if one item fails a unique index check.

Common Mistakes to Avoid

  • Inserting 10,000 rows in a for loop with await insertOne(): Sequential network round-trips make bulk imports painfully slow. Batch arrays in chunks of 500–1,000 documents using insertMany().
  • Passing raw req.body directly into insertOne(req.body): Users could inject unexpected fields like role: 'admin' or isPaid: true. Destructure only allowed fields explicitly before inserting.
  • Using deprecated insert() method: Modern mongodb v4+ drivers removed collection.insert(); always use insertOne() or insertMany().

Frequently Asked Questions

What does insertOne() return in the modern Node.js driver?

It returns { acknowledged: true, insertedId: ObjectId(...) } rather than the full inserted document.

Can I provide my own custom _id value?

Yes. Passing _id: 'order-2026-001' or a UUID string works fine as long as every _id in that collection remains unique.

What is the maximum size of a single MongoDB document?

Each BSON document can be up to 16 MB. Store large files in S3 or MongoDB GridFS instead of embedding giant binary blobs inside documents.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

Node.js Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum