Node.js MongoDB Delete

The delete operations in MongoDB allow you to remove documents from a collection. Using Node.js and the mongodb driver, you can perform deletions with various conditions.

 

Key Features of MongoDB Delete

  1. Delete One: Removes the first document that matches the query.
  2. Delete Many: Removes all documents that match the query.
  3. Efficient Deletion: Queries can be optimized using indexes for faster deletions.

 

Step 1 Prerequisites

Ensure you have MongoDB installed and running, and the mongodb package is installed in your project.

npm install mongodb

Step 2 Delete One Document

Delete the first document that matches the specified filter.

Example Code

const { MongoClient } = require('mongodb');

// Connection URL and Database Name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';

async function deleteOneDocument() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Delete one document where age is 30
    const result = await collection.deleteOne({ age: 30 });
    console.log(`${result.deletedCount} document(s) deleted`);
  } finally {
    await client.close();
  }
}

deleteOneDocument().catch(console.error);

Output:

1 document(s) deleted

Step 3 Delete Multiple Documents

Delete all documents that match a specified filter.

Example Code

async function deleteMultipleDocuments() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Delete all documents where age is greater than 25
    const result = await collection.deleteMany({ age: { $gt: 25 } });
    console.log(`${result.deletedCount} document(s) deleted`);
  } finally {
    await client.close();
  }
}

deleteMultipleDocuments().catch(console.error);

Output:

2 document(s) deleted

Step 4 Deleting Documents with No Matches

When the query does not match any document, no deletion occurs, but the operation is still considered successful.

Example Code

async function deleteNoMatch() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Attempt to delete where age is 100
    const result = await collection.deleteMany({ age: 100 });
    console.log(`${result.deletedCount} document(s) deleted`);
  } finally {
    await client.close();
  }
}

deleteNoMatch().catch(console.error);

Output:

0 document(s) deleted

Step 5 Delete All Documents

Delete all documents from a collection by using an empty filter.

Example Code

async function deleteAllDocuments() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Delete all documents in the collection
    const result = await collection.deleteMany({});
    console.log(`${result.deletedCount} document(s) deleted`);
  } finally {
    await client.close();
  }
}

deleteAllDocuments().catch(console.error);

Output:

5 document(s) deleted

Step 6 Drop a Collection

Remove an entire collection from the database.

Example Code

async function dropCollection() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);

    // Drop the 'users' collection
    const result = await db.collection('users').drop();
    console.log('Collection dropped:', result);
  } finally {
    await client.close();
  }
}

dropCollection().catch(console.error);

Output:

Collection dropped: true

 

Summary

MongoDB's delete operations using Node.js provide flexibility to remove single or multiple documents based on a variety of filters. For large-scale operations, ensure you use appropriate indexes and test queries to avoid accidental data loss. Always handle deletions carefully to maintain database integrity.