Chapter 6: MongoDB mongosh Insert
MongoDB mongosh Insert (aka How to add data using insertOne() and insertMany() in the mongosh shell)
This is the C in CRUD — Create / Insert operations. It’s how you bring new documents (your data records) into a collection.
1. The Two Main Insert Methods in mongosh (2026 Reality)
| Method | What it does | How many documents? | Returns (on success) | Most common use case |
|---|---|---|---|---|
| db.collection.insertOne(doc) | Inserts exactly one document | 1 | { acknowledged: true, insertedId: ObjectId(…) } | Adding single items (user signup, new post, log entry) |
| db.collection.insertMany([doc1, doc2, …]) | Inserts multiple documents in one call | Many | { acknowledged: true, insertedIds: { “0”: ObjectId(…), “1”: … } } | Bulk import, seeding data, adding many products/orders |
Important notes (teacher yelling gently):
- If the collection doesn’t exist → MongoDB creates it automatically.
- If the database doesn’t exist → it gets created too (as we learned earlier).
- Every document must have (or will get) a unique _id field.
- You can provide your own _id (string, number, etc.)
- Or let MongoDB auto-generate an ObjectId (most common & recommended).
Old method warning: db.collection.insert() (single doc or array) is deprecated since MongoDB 3.x / 4.x era. In 2026 you should always prefer insertOne() or insertMany().
2. Let’s Do It Hands-on — Step by Step
Assume you’re already in mongosh and switched to a database:
|
0 1 2 3 4 5 6 |
use valentines2026 |
Example 1: insertOne() — Single Document (The Hello World of Inserts)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
db.wishes.insertOne({ from: "Rahul", to: "Priya", message: "Happy Valentine's Day! You're my favorite query result ❤️", date: new Date(), emoji: "🌹🍫", rating: 10 }) |
What you see back (typical output):
|
0 1 2 3 4 5 6 7 8 9 |
{ acknowledged: true, insertedId: ObjectId('67abcdf1234567890fedcba9') } |
→ Success! One document added. → _id was auto-generated because we didn’t provide one.
Now verify:
|
0 1 2 3 4 5 6 |
db.wishes.find().pretty() |
You should see something like:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
{ "_id": ObjectId("67abcdf1234567890fedcba9"), "from": "Rahul", "to": "Priya", "message": "Happy Valentine's Day! You're my favorite query result ❤️", "date": ISODate("2026-02-14T07:35:00Z"), "emoji": "🌹🍫", "rating": 10 } |
Example 2: insertMany() — Multiple Documents at Once
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
db.wishes.insertMany([ { from: "Amit", to: "Sneha", message: "You make every aggregation feel simple!", date: new Date(), giftIdea: "Biryani date" }, { from: "Priya", to: "Rahul", message: "Thanks for the MongoDB lessons — best valentine gift!", date: new Date(), rating: 11, attachment: "photo_of_us.jpg" }, { from: "Class2026", to: "Everyone", message: "Keep querying with love!", date: new Date(), emojiCount: 5 } ]) |
Typical output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ acknowledged: true, insertedIds: { '0': ObjectId('67abcdf2234567890fedcbaa'), '1': ObjectId('67abcdf2234567890fedcbab'), '2': ObjectId('67abcdf2234567890fedcbac') } } |
→ Three new documents added in one round-trip to the server (efficient!).
Check them:
|
0 1 2 3 4 5 6 |
db.wishes.find().pretty() |
You’ll see all five wishes now (the one from before + these three).
Example 3: Providing Your Own _id (When You Want Control)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
db.products.insertOne({ _id: "BIRYANI-HYD-001", // your custom unique ID name: "Hyderabadi Chicken Dum Biryani", price: 380, spiceLevel: "Medium", available: true }) db.products.insertMany([ { _id: "COFFEE-001", name: "Filter Coffee", price: 60 }, { _id: "IDLI-001", name: "Podi Idli", price: 90 } ]) |
→ Useful when importing from another system or using natural keys (product codes, usernames, invoice numbers).
Warning: If you try to insert duplicate _id → you get error:
|
0 1 2 3 4 5 6 |
MongoServerError: E11000 duplicate key error collection... |
3. Useful Options You Can Add (Beginner to Intermediate)
Both methods accept an options object as second argument.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// insertOne with write concern (wait for majority confirmation) db.wishes.insertOne( { message: "Extra safe insert" }, { writeConcern: { w: "majority", wtimeout: 5000 } } ) // insertMany — stop on first error (default is true) db.products.insertMany( [ ...many docs... ], { ordered: false } // continue even if one fails (unordered bulk) ) |
4. Quick Cheat Sheet Table
| What you want to do | Command Example |
|---|---|
| Add one simple document | db.students.insertOne({ name: “Sneha”, age: 19 }) |
| Add many documents | db.movies.insertMany([ {title:”RRR”}, {title:”Kalki”} ]) |
| Use your own _id | db.users.insertOne({ _id: “rahul123”, email: “rahul@hyd.in” }) |
| Insert & get back the new _id | Look at insertedId or insertedIds in the result |
| Insert date properly | date: new Date() or ISODate(“2026-02-14”) |
| Bulk insert but don’t stop on error | insertMany([…], { ordered: false }) |
5. Mini Exercise — Do This Right Now!
- use myLoveDb2026
- Insert one wish for yourself:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
db.selfLove.insertOne({ from: "Me", to: "Me", message: "I'm proud of learning MongoDB today!", date: new Date(), mood: "Happy & Growing" }) |
- Insert 2-3 more for friends/classmates.
- db.selfLove.find().pretty() → admire your data!
Understood everything? This is the foundation — every app starts with inserts!
Next class — what shall we do?
- Find queries (read what we just inserted)?
- Update and Delete to complete CRUD?
- BulkWrite for mixed operations?
- Or start a tiny “Valentine Wishlist” mini-project?
Tell me — I’m ready with the next lesson! 🚀❤️
Any doubt in insert? Ask freely — no judgment here! 😄
