Beginner MongoDB

Deleting Documents in MongoDB

Remove documents from collections using deleteOne(), deleteMany(), and understand write concerns.

5 min read Tutorial

Deleting Documents

MongoDB provides deleteOne() and deleteMany() to remove documents from a collection. Both methods accept a filter document that determines which documents to remove.

deleteOne()

Removes the first document that matches the filter. This is useful when you want to delete a specific document by its unique identifier:

// Delete a specific user by email
db.users.deleteOne({ email: "bob@example.com" })

// Result:
// { acknowledged: true, deletedCount: 1 }

// Delete by _id
db.users.deleteOne({ _id: ObjectId("64a7b2c3d4e5f6a7b8c9d0e1") })

deleteMany()

Removes all documents that match the filter. Be careful -- this operation cannot be undone:

// Delete all inactive users
db.users.deleteMany({ status: "inactive" })

// Delete all orders older than 2023
db.orders.deleteMany({
  createdAt: { $lt: new Date("2023-01-01") }
})

// Delete ALL documents in a collection (use with caution!)
db.tempLogs.deleteMany({})

findOneAndDelete()

If you need to retrieve the document being deleted, use findOneAndDelete(). It atomically finds and removes the document, returning the deleted document:

// Remove and return the oldest pending job
const deletedJob = db.jobs.findOneAndDelete(
  { status: "pending" },
  { sort: { createdAt: 1 } }
)

// deletedJob contains the full document that was removed

Dropping a Collection

To remove an entire collection including all its documents and indexes, use drop():

// Drop the entire collection
db.tempLogs.drop()

// This is faster than deleteMany({}) for removing all documents
// because it also removes indexes

Write Concern

You can specify a write concern to control the level of acknowledgment for delete operations in a replica set:

// Ensure the delete is confirmed by the majority of nodes
db.orders.deleteMany(
  { status: "cancelled" },
  { writeConcern: { w: "majority", wtimeout: 5000 } }
)

Key Takeaways

  • deleteOne() removes the first match; deleteMany() removes all matches.
  • findOneAndDelete() returns the deleted document atomically.
  • Use drop() to remove an entire collection and its indexes.
  • Delete operations are permanent -- consider soft deletes for important data.

Try this query in UnifySQL

Write, optimize, and collaborate on MongoDB queries with AI assistance.

Start Free