Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 70 ยท CRUD: update and delete

Deleting Documents

Remove data with deleteOne and deleteMany, know when drop is better, use soft deletes, preview TTL expiry and build safe delete habits.

Deleting is the one write you cannot take back. There is no recycle bin and no undo button: once a delete is acknowledged, the documents are gone unless you have a backup. MongoDB gives you precise tools for the job, and a few habits make them safe to use.

In this lesson you will use deleteOne and deleteMany, learn the difference between emptying a collection and dropping it, see the soft delete pattern that keeps data but hides it, and get a first look at TTL indexes, which delete documents automatically after a time.

MongoDB cannot run on this site. The mongosh blocks are real commands shown read-only, and the runnable examples use a small stand-in engine in plain JavaScript that models the behavior. Result objects look like the real ones, but the engine only supports the operators the examples use.

Ways to remove data

deleteOne Remove one matching document.
deleteMany Remove every match.
drop Remove the whole collection.
Soft delete Mark it, keep it.
1 / 2

deleteOne and deleteMany

deleteOne(filter) removes at most one document, and deleteMany(filter) removes all documents that match. Both take the same filters you already know from Finding Documents.

JavaScript
db.sessions.deleteOne({ _id: ObjectId("66f0c0ffee0000000000abcd") })
db.sessions.deleteMany({ expiresAt: { $lt: new Date() } })

Both return a small result:

JavaScript
{ acknowledged: true, deletedCount: 1 }

deletedCount is how you check that the delete did what you meant. If you expected one document and got 0, the filter matched nothing; if you expected a handful and got thousands, stop and investigate.

Two details deserve attention:

  • deleteOne picks one match in no promised order. If several documents match, you cannot say which one goes. Delete by _id, or by a field that is unique, when it must be a specific document. If you need "the oldest one", use findOneAndDelete with a sort, which removes one document and returns it.
  • An empty filter matches everything. deleteMany({}) removes every document in the collection. Always write the filter explicitly, and never build it from user input without validation (see NoSQL Injection and Safe Queries).

Deleting by a value that is missing from a document does not match: { archived: false } does not match documents that have no archived field at all. If your data is inconsistent, a delete can silently leave some documents behind.

JS deleteOne and deleteMany

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The legacy remove() method

Old scripts delete with db.collection.remove(). It is deprecated, but it is easy to recognize once you know it maps onto the two modern methods:

JavaScript
db.orders.remove({ status: "cancelled" })                // like deleteMany(...)
db.orders.remove({ status: "cancelled" }, true)          // second argument justOne = true: like deleteOne(...)
db.orders.remove({ status: "cancelled" }, { justOne: true, writeConcern: { w: "majority" } })
db.orders.remove({})                                     // deletes EVERY document (like deleteMany({}))

Two traps explain why it was replaced. First, by default remove deletes all matching documents, whereas the shell's deleteOne name says exactly what it will do, so a forgotten justOne removes far more than intended. Second, the result is a WriteResult with an nRemoved count, not deletedCount. In new code use deleteOne/deleteMany, build the filter with the same care, and test it with find() first.

Emptying versus dropping

deleteMany({}) removes every document but keeps the collection, its indexes and its settings. It also works document by document, which is slow for a very large collection.

db.collection.drop() removes the whole collection including its indexes in one fast operation, and it returns true if it existed. After a drop, you must recreate any indexes and validation rules. To remove a whole database, use db.dropDatabase().

Goal Command
Remove a few documents deleteOne / deleteMany(filter)
Empty a collection, keep indexes deleteMany({})
Throw the collection away, indexes too drop()
Throw the whole database away db.dropDatabase()

Dropping a collection that something else still uses is a classic outage. In production, restrict who may drop collections (see Authentication and Role-Based Access).

Soft deletes

A soft delete does not remove the document. It marks it, usually with a timestamp, and every normal query ignores marked documents:

JavaScript
db.articles.updateOne(
  { _id: 7 },
  { $set: { deletedAt: new Date() } }
)

db.articles.find({ deletedAt: { $exists: false } })

Soft deletes give you an undo button, an audit trail, and a way to keep references valid (an order that points at a deleted product still has something to show). The price is real:

  • Every query must filter the marked documents out. One forgotten filter shows deleted data to users. Wrap the filter in one function or view so you cannot forget.
  • The collection grows and indexes include dead documents. A partial index (for example, only documents without deletedAt) keeps hot indexes small.
  • Uniqueness gets awkward: a deleted user's email still occupies a unique index.
  • Privacy rules such as "erase my data" may require a real delete in the end. Often the answer is a soft delete first and a scheduled hard delete later.
JS Soft delete with a scheduled purge

Press Run (or Ctrl + Enter) to see the console output here.

No output.

TTL indexes: delete by schedule

Many documents have a natural lifetime: sessions, password-reset tokens, cache entries. A TTL index (time to live) tells MongoDB to delete them for you. You create it on a date field and give it a number of seconds:

JavaScript
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })

A background task checks the index about once a minute and removes documents whose date is older than expireAfterSeconds. That means expiry is approximate: a document may live up to a minute or so past its deadline, and on a busy server a little longer. Never use it where you must hide data at the exact second. Add expiresAt <= now to the query as well if it matters.

Two more rules: the indexed field must hold a BSON date (or an array of dates), and a TTL index must be on a single field. You can also set each document's own expiry time by indexing an expiresAt field with expireAfterSeconds: 0. Indexes get a full treatment in How Indexes Work and Index Types.

JS A TTL sweep, simulated

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Safe delete habits

  1. Preview first. Run find with the exact filter you will delete with. Better: countDocuments(filter) and check that the number is plausible.
  2. Delete by _id when you can. It is unambiguous and cheap.
  3. Check deletedCount. Treat a surprising number as an error in your code.
  4. Never trust the empty filter. Make sure variables used in a filter are not undefined or empty; code that builds { userId: input } with a missing input may behave differently than you expect.
  5. Have a backup you have restored at least once (see Backup, Restore and Import/Export).
  6. Prefer soft deletes for business data, TTL for disposable data, and hard deletes for what must truly vanish.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does db.users.deleteMany({}) do?

    An empty filter matches all documents. The collection itself, its indexes and its settings stay.
  2. 2. Which is the main difference between drop() and deleteMany({})?

    After drop() you must recreate indexes and validation rules; after deleteMany({}) they are still there.
  3. 3. What is a drawback of soft deletes?

    A forgotten filter exposes deleted data, and the collection keeps growing. A single helper or view makes the filter hard to forget.
  4. 4. A TTL index has expireAfterSeconds: 3600. When is a document removed?

    The expiry is approximate. Add an explicit date condition to queries if you need exact hiding.
  5. 5. Two documents match deleteOne({ status: "old" }). Which one is deleted?

    deleteOne has no sort option. Delete by _id, or use findOneAndDelete with a sort.

Summary

  • deleteOne removes one match and deleteMany removes all of them; both return deletedCount.
  • An empty filter matches every document, so write filters explicitly and verify them first.
  • deleteMany({}) empties a collection but keeps indexes; drop() removes the collection and its indexes.
  • Soft deletes mark documents instead of removing them, at the cost of extra filtering and storage.
  • TTL indexes delete expired documents automatically, roughly once a minute and not to the second.
  • Preview, count, back up and prefer deleting by _id.

Next, send many writes at once with Bulk Writes.