KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
🟢

Node.js

Topic Hub & Articles

Node.js Intro

10 min

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Node.js Buffer

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Streams

10 min

Node.js Crypto

10 min

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Node.js DNS Module

10 min

Node.js Query String

10 min

Recap Quiz

Gated

Milestone Assessment

MySQL Connect

10 min

MySQL Create Database

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js MySQL ORDER BY Clause

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Intro

10 min

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

MongoDB Delete

10 min

MongoDB Update

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Node.jsNode.js MongoDB
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.

Related Developer Tools & Topic Hub

Node.js Topic Hub
JSON Formatter
Validate, format, and minify JSON
Regex Tester
Test regular expression patterns
JWT Decoder
Inspect JSON Web Token payloads
All Node.js Articles
Deep-dive guides, tips & discussions
PreviousMongoDB Create Collection
Continue JourneyTake Recap Quiz

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum