MongoDB mongosh Insert

MongoDB Tutorial

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

mongosh

2️⃣ Switch to Database

use myDatabase

 If the database doesn’t exist, MongoDB will create it when data is inserted.


3️⃣ Insert One Document (Most Common)

Syntax

db.collection.insertOne(document)

Example


 

Output

{
acknowledged: true,
insertedId: ObjectId("...")
}

Automatically:

  • Creates database (if not exists)

  • Creates collection (if not exists)


4️⃣ Insert Multiple Documents

Syntax

db.collection.insertMany([document1, document2, ...])

Example



 

Output

{
acknowledged: true,
insertedIds: {
"0": ObjectId("..."),
"1": ObjectId("..."),
"2": ObjectId("...")
}
}

5️⃣ View Inserted Data

db.users.find()

Formatted output:

db.users.find().pretty()

6️⃣ Insert Document with Custom _id (Interview Tip)



 

_id must be unique.


7️⃣ Insert Without Some Fields (Schema-less Nature)

db.users.insertOne({
name: "Anita"
})

✔ MongoDB allows different fields in different documents.


8️⃣ Old Method: insert() (Exam Note)

db.users.insert({
name: "Old User",
age: 50
})

Works but not recommended (deprecated).


9️⃣ What Happens If Duplicate _id?

db.users.insertOne({
_id: 101,
name: "Duplicate"
})

 Error:

E11000 duplicate key 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

use myDatabase
db.users.insertOne({ name: "Amit", age: 25 })
db.users.insertMany([{...}, {...}])
db.users.find()

That’s everything you need to know about INSERT in MongoDB using mongosh.

You may also like...