MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Insert Operations: insertOne, insertMany & Write Concerns0%
Study Materials
MongoDB & MongooseProgress 0%
1.1Document Databases vs Relational SQL: CAP Theorem & When to Use NoSQL1.2JSON vs BSON Data Types & MongoDB Internal Storage Engine (WiredTiger)1.3MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUI
2.1Insert Operations: insertOne, insertMany & Write Concerns2.2Find Queries & Comparison Operators ($eq, $gt, $in, $nin)2.3Logical, Element & Array Query Operators ($and, $or, $exists, $all)2.4Update Operations: updateOne, updateMany & Field Modifiers ($set, $inc, $push)2.5Delete Operations, Cursors, Limit, Skip & Sorting in MongoDB
HomeTutorialsMongoDB & MongooseInsert Operations: insertOne, insertMany & Write Concerns
Find Queries & Comparison Operators ($eq, $gt, $in, $nin)

Insert Operations: insertOne, insertMany & Write Concerns

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Writing documents into MongoDB is the initial step in any data lifecycle. MongoDB provides high-throughput insert methods with granular control over batch processing, ordered execution, and Write Concerns.


1. Inserting a Single Document: insertOne()

The insertOne() method inserts a single document into a collection. If the document does not contain a top-level _id field, the driver generates an ObjectId automatically.

1// Inserting into 'courses' collection
2const result = await db.collection('courses').insertOne({
3 title: 'Full-Stack MERN Mastery',
4 slug: 'full-stack-mern-mastery',
5 price: 4999,
6 category: 'Web Development',
7 isPublished: true,
8 tags: ['react', 'node', 'mongodb', 'express'],
9 instructor: {
10 name: 'Sumit Sharma',
11 experienceYears: 10
12 },
13 createdAt: new Date()
14});
15 
16console.log('Inserted ID:', result.insertedId);
17console.log('Acknowledged:', result.acknowledged); // true

2. Inserting Multiple Documents: insertMany()

To insert multiple records in a single network round-trip, pass an array of documents to insertMany():

1const students = [
2 { name: 'Aarav Patel', email: 'aarav@example.com', enrolledAt: new Date() },
3 { name: 'Priya Sharma', email: 'priya@example.com', enrolledAt: new Date() },
4 { name: 'Rohan Gupta', email: 'rohan@example.com', enrolledAt: new Date() }
5];
6 
7const batchResult = await db.collection('students').insertMany(students, {
8 ordered: true // Default: stops on first error. Set to false for unordered inserts.
9});
10 
11console.log('Inserted Count:', batchResult.insertedCount);
12console.log('Inserted IDs:', batchResult.insertedIds);

Ordered vs Unordered Inserts:

  • ordered: true (Default): MongoDB processes documents sequentially. If document 2 fails (e.g. duplicate key), the operation halts immediately. Documents after 2 are not inserted.
  • ordered: false: MongoDB attempts to insert all documents in parallel. If document 2 fails, MongoDB reports the error but continues inserting documents 3, 4, etc.

3. Understanding Write Concerns (w)

A Write Concern describes the level of acknowledgment requested from MongoDB for write operations:

  • w: 1 (Acknowledged): The Primary node acknowledges the write has been written to memory/journal. Fast, standard default.
  • w: "majority": The write must be committed by a majority of replica set members before returning success. Protects against data loss during sudden primary failover.
  • j: true (Journaled): Guarantees the write has been written to the on-disk journal before responding.
1// High-security financial transaction write concern:
2await db.collection('transactions').insertOne(
3 { accountId: 'acc_01', amount: 50000, type: 'CREDIT' },
4 { writeConcern: { w: 'majority', j: true, wtimeoutMS: 5000 } }
5);

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What happens if you insert a document into a MongoDB collection without providing an _id field?
Question 2
In collection.insertMany(docs, { ordered: true }), what occurs if the 3rd document violates a unique index constraint?
Question 3
How do you instruct insertMany() to continue inserting remaining documents even if one document in the batch fails?
Question 4
What does the write concern option { w: 'majority' } guarantee?
Question 5
What property on the result object of collection.insertOne() contains the generated primary key?

Next Lesson

Find Queries & Comparison Operators ($eq, $gt, $in, $nin)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
MongoDB Atlas Cloud Setup, Network Whitelisting & Compass GUIFind Queries & Comparison Operators ($eq, $gt, $in, $nin)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master MongoDB & Mongoose with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext