MongoDB mongosh Delete

MongoDB mongosh – Delete Documents 🗑️

In MongoDB, delete operations are used to remove documents from a collection.

Be careful ⚠️—deleted data cannot be recovered unless you have backups.


1️⃣ Delete a Single Document (deleteOne)

Syntax

db.collection.deleteOne(filter)

Example

db.students.deleteOne({ name: "Riya" })

Output

acknowledged: true
deletedCount: 1

📌 Deletes only the first matching document.


2️⃣ Delete Multiple Documents (deleteMany)

db.students.deleteMany({ course: "BA" })

Deletes all documents matching the condition.


3️⃣ Delete All Documents in a Collection ⚠️

db.students.deleteMany({})

✅ Collection remains
❌ All documents removed


4️⃣ Delete Using Conditions

Greater than / Less than

db.students.deleteMany({ age: { $lt: 18 } })

Logical Operator

db.students.deleteMany({
$or: [
{ course: "BA" },
{ course: "BSc" }
]
})

5️⃣ Delete by _id

db.students.deleteOne({ _id: ObjectId("64f1abc123...") })

📌 _id is unique → deletes exactly one document.


6️⃣ Check Before Deleting (Best Practice 👍)

Always preview data before deleting:

db.students.find({ course: "BA" })

Then delete:

db.students.deleteMany({ course: "BA" })

7️⃣ Drop Collection (Deletes Structure + Data)

db.students.drop()

Output:

true

⚠️ Collection is permanently removed.


SQL vs MongoDB (DELETE)

SQL

DELETE FROM students WHERE course = 'BA';

MongoDB

db.students.deleteMany({ course: "BA" })

Common Mistakes ⚠️

  • Using {} accidentally (deletes everything)

  • Forgetting filter condition

  • Confusing deleteMany() with drop()


Quick Recap 🧠

deleteOne() // delete single document
deleteMany() // delete multiple documents
drop() // delete collection

You may also like...