MongoDB Delete
Deleting documents works like updating them: a filter selects the documents, and the method decides how many are removed.
| Method | Deletes | Returns |
|---|---|---|
deleteOne(filter) |
the first matching document | { acknowledged, deletedCount } |
deleteMany(filter) |
every matching document | { acknowledged, deletedCount } |
findOneAndDelete(filter, options) |
the first match | the deleted document itself |
deleteOne
const r = db.orders.deleteOne({ _id: 1017 });
print(r);
print(db.orders.findOne({ _id: 1017 }));
print(db.orders.countDocuments());{ acknowledged: true, deletedCount: 1 }
null
19
When the filter matches several documents, deleteOne removes only the first one in natural order. Filter by _id (or another unique field) when you mean one specific document.
deleteMany
print(db.orders.countDocuments({ status: 'cancelled' }));
const res = db.orders.deleteMany({ status: 'cancelled' });
print('deleted:', res.deletedCount);
print(db.orders.distinct('status'));2
deleted: 2
[ 'delivered', 'processing', 'shipped' ]
Any filter you could use in find() works here, including operators. This removes all sold-out snacks:
const gone = db.products.deleteMany({ category: 'snacks', stock: { $lte: 0 } });
print(gone.deletedCount);
print(db.products.find({ category: 'snacks' }, { _id: 0, name: 1, stock: 1 }).toArray());1
[
{ name: 'Almond Biscotti', stock: 50 },
{ name: 'Dark Chocolate Bar', stock: 75 },
{ name: 'Salted Pretzels', stock: 40 }
]
Deleting everything
deleteMany({}) removes every document but keeps the collection, its indexes and its validation rules:
db.customers.createIndex({ email: 1 });
db.customers.deleteMany({});
print(db.customers.countDocuments());
print(db.customers.getIndexes().map(i => i.name));0
[ '_id_', 'email_1' ]
Warning: There is no undo and no "Are you sure?" prompt. A typo in the filter, or an empty filter, can wipe a collection. Run the same filter with
countDocuments()orfind()first to see what you are about to delete.
findOneAndDelete
Sometimes you need the document you remove, for example to process a job from a queue. findOneAndDelete deletes and returns it in one atomic step, so two workers can never take the same job. The sort option decides which match comes first:
db.jobs.insertMany([
{ _id: 1, task: 'send receipt', priority: 2 },
{ _id: 2, task: 'restock beans', priority: 1 },
{ _id: 3, task: 'email newsletter', priority: 3 }
]);
const next = db.jobs.findOneAndDelete({}, { sort: { priority: 1 } });
print('working on:', next.task);
print('left:', db.jobs.find().toArray().map(j => j.task));working on: restock beans
left: [ 'send receipt', 'email newsletter' ]
Soft deletes
Many applications never physically delete important records like orders. Instead they mark them, which keeps history and makes mistakes reversible:
db.orders.updateOne({ _id: 1006 }, { $set: { deleted: true } });
const visible = db.orders.countDocuments({ deleted: { $ne: true } });
print('visible orders:', visible);visible orders: 19
Every query then has to include deleted: { $ne: true }, which is the price of this pattern.
Test yourself
What does db.orders.deleteMany({}) do?
- Nothing; the filter is empty
- Deletes every order but keeps the collection and its indexes
- Drops the orders collection
- Deletes the first order
Which method returns the document it deleted?
- deleteOne
- deleteMany
- findOneAndDelete
- remove