0
0
MongodbHow-ToBeginner · 3 min read

How to Use deleteOne in MongoDB: Syntax and Examples

In MongoDB, use deleteOne(filter) to remove the first document that matches the filter criteria from a collection. It deletes only one matching document and returns a result indicating success or failure.
📐

Syntax

The deleteOne() method takes a filter object to specify which document to delete. It removes the first document that matches this filter.

  • filter: An object that defines the condition to find the document to delete.
mongodb
db.collection.deleteOne(filter)
💻

Example

This example shows how to delete one document where the name field is "Alice" 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');

    // Insert sample documents
    await users.insertMany([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Alice', age: 28 }
    ]);

    // Delete one document where name is 'Alice'
    const result = await users.deleteOne({ name: 'Alice' });
    console.log('Deleted count:', result.deletedCount);

    // Find remaining documents
    const remaining = await users.find().toArray();
    console.log('Remaining documents:', remaining);
  } finally {
    await client.close();
  }
}

run().catch(console.dir);
Output
Deleted count: 1 Remaining documents: [ { name: 'Bob', age: 30 }, { name: 'Alice', age: 28 } ]
⚠️

Common Pitfalls

Common mistakes when using deleteOne() include:

  • Using an empty filter {} unintentionally deletes the first document in the collection.
  • Expecting deleteOne() to delete multiple documents; it only deletes one.
  • Not checking the deletedCount in the result to confirm if a document was deleted.
mongodb
/* Wrong: Deletes first document without filter */
db.collection.deleteOne({});

/* Right: Specify filter to delete a specific document */
db.collection.deleteOne({ _id: someObjectId });
📊

Quick Reference

MethodDescription
deleteOne(filter)Deletes the first document matching the filter.
filterAn object specifying the condition to find the document.
deletedCountNumber of documents deleted (0 or 1).

Key Takeaways

Use deleteOne(filter) to remove a single matching document from a MongoDB collection.
Always provide a filter to avoid deleting unintended documents.
Check the deletedCount property in the result to confirm deletion.
deleteOne deletes only one document even if multiple match the filter.
Avoid using empty filters unless you want to delete the first document in the collection.