MongoDB mongosh Insert

MongoDB mongosh – Insert Documents 📝

In MongoDB, inserting data means adding documents to a collection.

MongoDB provides simple and powerful insert methods in mongosh.


1️⃣ Insert a Single Document (insertOne)

Syntax

db.collection.insertOne(document)

Example

db.students.insertOne({
name: "Amit",
age: 21,
course: "BA"
})

Output

acknowledged: true
insertedId: ObjectId("...")

📌 If the collection does not exist, MongoDB creates it automatically.


2️⃣ Insert Multiple Documents (insertMany)

Syntax

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

Example

db.students.insertMany([
{ name: "Riya", age: 20, course: "BSc" },
{ name: "Suman", age: 22, course: "BA" },
{ name: "Karan", age: 23, course: "BCom" }
])

Output

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

3️⃣ Insert with Custom _id

MongoDB automatically creates _id, but you can define it yourself.

db.students.insertOne({
_id: 101,
name: "Neha",
age: 19,
course: "BA"
})

⚠️ _id must be unique.


4️⃣ Insert Nested (Embedded) Documents

db.students.insertOne({
name: "Rahul",
age: 22,
address: {
city: "Delhi",
state: "Delhi"
},
subjects: ["Math", "Physics"]
})

5️⃣ Verify Inserted Data

db.students.find().pretty()

6️⃣ Insert with Write Concern (Basic)

db.students.insertOne(
{ name: "Vikas", age: 24 },
{ writeConcern: { w: "majority" } }
)

7️⃣ Common Insert Errors ⚠️

Duplicate _id Error

E11000 duplicate key error collection

Invalid Document

  • Circular references

  • Unsupported data types


SQL vs MongoDB (INSERT)

SQL

INSERT INTO students VALUES ('Amit', 21, 'BA');

MongoDB

db.students.insertOne({ name: "Amit", age: 21, course: "BA" })

Quick Summary 🧠

insertOne() // insert single document
insertMany() // insert multiple documents
_id // unique identifier

You may also like...