0
0
MongoDBquery~5 mins

deleteOne method in MongoDB

Choose your learning style9 modes available
Introduction

The deleteOne method removes a single document from a MongoDB collection that matches a given condition. It helps keep your data clean by deleting unwanted or outdated information.

You want to remove a specific user from a list based on their ID.
You need to delete one outdated product from your inventory.
You want to remove a single comment from a blog post.
You want to delete one record that matches a certain condition, like a status or date.
You want to clean up one incorrect or duplicate entry in your database.
Syntax
MongoDB
db.collection.deleteOne(filter, options)

filter is an object that specifies which document to delete.

options is optional and can control things like write concern.

Examples
Deletes one user document where the name is "Alice".
MongoDB
db.users.deleteOne({ name: "Alice" })
Deletes one product with a price less than 10.
MongoDB
db.products.deleteOne({ price: { $lt: 10 } })
Deletes one order with status "cancelled" and waits for majority confirmation.
MongoDB
db.orders.deleteOne({ status: "cancelled" }, { writeConcern: { w: "majority" } })
Sample Program

This example first adds three items to the items collection. Then it deletes one document where the name is "Pen". Finally, it shows the remaining documents.

MongoDB
use shopDB

// Insert sample documents
db.items.insertMany([
  { name: "Pen", price: 1.5 },
  { name: "Notebook", price: 3 },
  { name: "Pen", price: 2 }
])

// Delete one document where name is "Pen"
db.items.deleteOne({ name: "Pen" })

// Find all remaining documents
db.items.find().toArray()
OutputSuccess
Important Notes

deleteOne deletes only the first matching document it finds.

If no document matches the filter, nothing is deleted and no error occurs.

Always double-check your filter to avoid deleting the wrong document.

Summary

deleteOne removes a single document matching your filter.

It is useful for deleting specific entries without affecting others.

Use clear filters to target the right document safely.