How to Use deleteMany in MongoDB: Syntax and Examples
In MongoDB, use
deleteMany(filter) to remove all documents that match the given filter. This method deletes multiple documents at once and returns a result object with the count of deleted documents.Syntax
The deleteMany() method takes a filter object to specify which documents to delete. It removes all documents matching this filter from the collection.
- filter: A query object to match documents for deletion.
The method returns a result object containing deletedCount, which shows how many documents were deleted.
mongodb
db.collection.deleteMany(filter)Example
This example deletes all documents where the field status is "inactive" from the users collection.
javascript
const { MongoClient } = require('mongodb'); async function run() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const db = client.db('testdb'); const users = db.collection('users'); // Delete all users with status 'inactive' const result = await users.deleteMany({ status: 'inactive' }); console.log(`${result.deletedCount} documents were deleted.`); } finally { await client.close(); } } run().catch(console.dir);
Output
3 documents were deleted.
Common Pitfalls
Common mistakes when using deleteMany() include:
- Using an empty filter
{}unintentionally deletes all documents in the collection. - Not awaiting the asynchronous operation in Node.js can cause unexpected behavior.
- Confusing
deleteMany()withdeleteOne(), which deletes only one matching document.
mongodb
/* Wrong: Deletes all documents unintentionally */ db.collection.deleteMany({}); /* Right: Specify a filter to delete only matching documents */ db.collection.deleteMany({ status: 'inactive' });
Quick Reference
| Method | Description |
|---|---|
| deleteMany(filter) | Deletes all documents matching the filter. |
| deleteOne(filter) | Deletes the first document matching the filter. |
| filter | A query object to select documents to delete. |
| deletedCount | Number of documents deleted returned in result. |
Key Takeaways
Use deleteMany(filter) to remove all documents matching the filter in a collection.
Always specify a filter to avoid deleting all documents unintentionally.
deleteMany returns a result with deletedCount showing how many documents were removed.
In Node.js, await deleteMany to ensure the operation completes before proceeding.
deleteMany differs from deleteOne, which deletes only a single matching document.