MongoDB mongosh Insert
MongoDB mongosh Insert Data
In MongoDB mongosh Insert data is stored as documents (JSON-like objects) inside collections.
You insert data using insert commands in mongosh.
1️⃣ Start mongosh
2️⃣ Switch to Database
If the database doesn’t exist, MongoDB will create it when data is inserted.
3️⃣ Insert One Document (Most Common)
Syntax
Example
Output
Automatically:
-
Creates database (if not exists)
-
Creates collection (if not exists)
4️⃣ Insert Multiple Documents
Syntax
Example
Output
5️⃣ View Inserted Data
Formatted output:
6️⃣ Insert Document with Custom _id (Interview Tip)
_idmust be unique.
7️⃣ Insert Without Some Fields (Schema-less Nature)
✔ MongoDB allows different fields in different documents.
8️⃣ Old Method: insert() (Exam Note)
Works but not recommended (deprecated).
9️⃣ What Happens If Duplicate _id?
Error:
Key Points (Very Important for Exams & Interviews)
✔ MongoDB uses documents, not rows
✔ Data is stored in BSON (Binary JSON)
✔ insertOne() → inserts single document
✔ insertMany() → inserts multiple documents
✔ _id is auto-generated if not provided
✔ No fixed schema required
Common Interview Questions
Q1. Which command inserts one document?
👉 insertOne()
Q2. Can MongoDB insert multiple documents at once?
👉 ✅ Yes, using insertMany()
Q3. What is _id in MongoDB?
👉 Unique identifier for each document
Q4. Does insert create collection automatically?
👉 ✅ Yes
Summary
That’s everything you need to know about INSERT in MongoDB using
mongosh.
