Delete Operations
Sometimes you need to remove data from your database – old records, spam comments, or test data. MongoDB provides two main methods for deletion: `deleteOne()` and `deleteMany()`. Let's learn how to use them safely.
deleteOne() - Delete First Matching Document
`deleteOne()` removes the first document that matches the filter. Even if multiple documents match, only one is deleted.
<!-- Delete a user named John -->db.users.deleteOne({ name: "John" })Output:
{ acknowledged: true, deletedCount: 1}Think of `deleteOne()` like carefully removing one specific book from a shelf. `deleteMany()` is like clearing an entire section.
deleteMany() - Delete All Matching Documents
`deleteMany()` removes all documents that match the filter. Be careful with this one!
<!-- Delete all inactive users -->db.users.deleteMany({ active: false })
<!-- Delete all products in the "toys" category -->db.products.deleteMany({ category: "toys" })
<!-- Delete all documents in a collection (use with caution!) -->db.products.deleteMany({})Deleting with Conditions
You can use query operators to delete documents that meet specific criteria:
<!-- Delete users older than 60 -->db.users.deleteMany({ age: { $gt: 60 } })
<!-- Delete products with zero stock -->db.products.deleteMany({ stock: 0 })
<!-- Delete posts with no tags -->db.posts.deleteMany({ tags: { $size: 0 } })Practical Examples
Let's create some data and then delete it:
<!-- Insert sample data -->db.orders.insertMany([ { item: "Laptop", quantity: 1, status: "shipped" }, { item: "Mouse", quantity: 2, status: "pending" }, { item: "Keyboard", quantity: 1, status: "shipped" }, { item: "Monitor", quantity: 1, status: "cancelled" }])
<!-- Delete cancelled orders -->db.orders.deleteMany({ status: "cancelled" })<!-- Output: { deletedCount: 1 } -->
<!-- Delete one pending order -->db.orders.deleteOne({ status: "pending" })<!-- Output: { deletedCount: 1 } -->
<!-- Check remaining orders -->db.orders.find().pretty()<!-- Only shipped orders remain -->Important Safety Tips
- Always check your filter first – Run `find()` with the same filter to see what will be deleted.
- Be careful with empty filters – `deleteMany({})` deletes EVERYTHING in the collection.
- There's no undo – Deletions are permanent (unless you have backups).
Safe Deletion Practice
<!-- 1. First, check what will be deleted -->db.orders.find({ status: "cancelled" }).pretty()
<!-- 2. If it looks right, then delete -->db.orders.deleteMany({ status: "cancelled" })Two Minute Drill
- `deleteOne()` removes the first document matching the filter.
- `deleteMany()` removes all documents matching the filter.
- Always verify your filter with `find()` before deleting.
- `deleteMany({})` deletes all documents – use with extreme caution.
- Deletions are permanent – there's no undo!
Need more clarification?
Drop us an email at career@quipoinfotech.com
