0
0
MongodbHow-ToBeginner · 3 min read

How to Delete a Document in MongoDB: Syntax and Examples

To delete a document in MongoDB, use the deleteOne() method to remove a single matching document or deleteMany() to remove multiple documents. Both methods take a filter object to specify which documents to delete.
📐

Syntax

The deleteOne() method deletes the first document that matches the filter. The deleteMany() method deletes all documents matching the filter.

  • filter: An object specifying the condition to find documents to delete.
  • callback (optional): A function to handle the result or error.
mongodb
db.collection.deleteOne(filter)
db.collection.deleteMany(filter)
💻

Example

This example shows how to delete one document where the field name is "Alice" and how to delete all documents where status is "inactive".

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 one document where name is 'Alice'
    const deleteOneResult = await users.deleteOne({ name: 'Alice' });
    console.log('Deleted documents count (deleteOne):', deleteOneResult.deletedCount);

    // Delete many documents where status is 'inactive'
    const deleteManyResult = await users.deleteMany({ status: 'inactive' });
    console.log('Deleted documents count (deleteMany):', deleteManyResult.deletedCount);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Deleted documents count (deleteOne): 1 Deleted documents count (deleteMany): 3
⚠️

Common Pitfalls

Common mistakes when deleting documents in MongoDB include:

  • Not specifying a filter, which can delete all documents unintentionally.
  • Using deleteOne() when you want to delete multiple documents.
  • Confusing remove() (deprecated) with deleteOne() or deleteMany().

Always double-check your filter to avoid accidental data loss.

mongodb
/* Wrong: Deletes all documents because filter is empty */
db.collection.deleteMany({});

/* Right: Deletes only documents where age is less than 18 */
db.collection.deleteMany({ age: { $lt: 18 } });
📊

Quick Reference

MethodDescriptionDeletes
deleteOne(filter)Deletes the first document matching the filterOne document
deleteMany(filter)Deletes all documents matching the filterMultiple documents

Key Takeaways

Use deleteOne() to remove a single document matching a filter.
Use deleteMany() to remove all documents matching a filter.
Always specify a filter to avoid deleting unintended documents.
Avoid using deprecated remove() method; prefer deleteOne() or deleteMany().
Check the deletedCount property to confirm how many documents were deleted.