LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 1711 min read

Deleting Documents

Remove documents from a collection using deleteOne and deleteMany.

deleteOne

deleteOne() removes the first document matching a filter.

db.users.deleteOne({ email: "ada@example.com" });

deleteMany

deleteMany() removes every document matching a filter — including, dangerously, every document in the collection if the filter is empty.

db.sessions.deleteMany({ expiresAt: { $lt: new Date() } }); // remove expired sessions
db.sessions.deleteMany({}); // removes EVERY document

Checking Before You Delete

Running the exact same filter through find() (or countDocuments()) first is a simple, effective habit for confirming exactly what a delete is about to remove, before it actually happens.

db.sessions.find({ expiresAt: { $lt: new Date() } }); // preview what will be deleted
db.sessions.deleteMany({ expiresAt: { $lt: new Date() } }); // then actually delete it
There Is No Undo

Unlike some databases with a built-in recycle bin, a MongoDB delete is immediate and permanent — always double check your filter (and consider a backup, covered later in this course) before running deleteMany in production.

Common Beginner Mistakes

Running deleteMany({}) by accident

An empty filter object matches everything — always pass a real, deliberate filter for anything other than genuinely clearing an entire collection.

Deleting instead of soft-deleting when history matters

For data where you might need an audit trail, consider a "soft delete" pattern — setting a deletedAt field with $set instead of physically removing the document.

FAQs

No — MongoDB has no built-in cascading delete across collections; your application logic (or a transaction, covered later) is responsible for cleaning up related references if needed.

Yes — db.collection.drop() removes the whole collection (including its indexes), which is more efficient than deleteMany({}) when you truly want to start fresh.

Summary

deleteOne and deleteMany remove documents matching a filter, permanently and immediately — always verify the filter first. Next, you'll learn upserts and bulk write operations.

Next Lesson →

Upserts & Bulk Writes