Lesson 12 +10 XP

Delete Documents

Delete Documents

Deleting is the "D" in CRUD. MongoDB gives you deleteOne() and deleteMany(), both taking a query object.

Delete the first match

db.posts.deleteOne({ title: "Post Title 5" })

Removes only the first document matching the query.

Delete all matches

db.posts.deleteMany({ category: "Technology" })

Removes every document matching the query.

Delete everything

An empty query matches all documents:

db.posts.deleteMany({})

Be careful!

deleteMany and deleteOne are permanent - there's no undo. Always double-check your query before running a delete.

Method summary

MethodWhat it deletes
deleteOne()First matching document
deleteMany()All matching documents

TL;DR

  • deleteOne(query) deletes the first matching document.
  • deleteMany(query) deletes all matching documents.
  • Deletes are permanent - verify your query first.