MongoDB Delete Documents

Deleting documents is a crucial operation in any database management system, including MongoDB. The delete operations in MongoDB allow you to remove specific documents or entire datasets from a collection based on your criteria.

Key Features of MongoDB Delete Operations

  1. deleteOne: Deletes a single document matching the specified condition.
  2. deleteMany: Deletes multiple documents that match the given condition.
  3. Flexible Conditions: Use query operators for precise deletion.
  4. Permanent Deletion: Deleted documents cannot be recovered unless backed up.

Prerequisites

  1. MongoDB Installed: Download MongoDB from mongodb.com.
  2. Node.js Installed: Download and install Node.js from nodejs.org.
  3. MongoDB Shell or Compass: Use either for database management.

Method 1: Delete Documents Using MongoDB Shell

Step 1: Open the MongoDB Shell

Run the following command:

mongosh

Step 2: Switch to a Database

Select the database you want to use:

use myDatabase

Step 3: Delete a Single Document

Use deleteOne to delete the first document that matches a condition:

db.users.deleteOne({ name: 'Alice' });

Explanation:

  • Condition: { name: ‘Alice’ } matches the document where the name field equals ‘Alice’.
  • Result: Deletes one document even if multiple documents match the condition.

Step 4: Delete Multiple Documents

Use deleteMany to delete all matching documents:

db.users.deleteMany({ age: { $gt: 30 } });

Explanation:

  • Condition: { age: { $gt: 30 } } matches documents where the age field is greater than 30.
  • Result: Deletes all documents that meet the condition.

Method 2: Delete Documents Using Node.js

Step 1: Install MongoDB Driver

Run the following command to install the MongoDB driver:

npm install mongodb

Step 2: Perform Delete Operations in Node.js

Create a file named app.js and write the following code:

Delete a Single Document

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

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myDatabase';

async function deleteOneDocument() {
try {
await client.connect();
console.log('Connected successfully to MongoDB');

const db = client.db(dbName);
const collection = db.collection('users');

// Delete a single document
const result = await collection.deleteOne({ name: 'Alice' });
console.log('Deleted document count:', result.deletedCount);
} catch (err) {
console.error('Error deleting document:', err);
} finally {
await client.close();
}
}

deleteOneDocument();

Delete Multiple Documents

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

// Delete multiple documents
const result = await collection.deleteMany({ age: { $lt: 25 } });
console.log('Deleted document count:', result.deletedCount);
} catch (err) {
console.error('Error deleting documents:', err);
} finally {
await client.close();
}
}

deleteManyDocuments();

Method 3: Delete Documents Using MongoDB Compass

Step 1: Open MongoDB Compass

  1. Launch MongoDB Compass and connect to your MongoDB server (mongodb://localhost:27017).
  2. Select your database and collection.

Step 2: Delete Documents

  1. Filter documents using the query box, e.g., { age: { $gt: 30 } }.
  2. Click “Delete Documents” to remove the matching documents.

Deleting a Collection

You can delete an entire collection using the drop method.

Example: Drop a Collection in Shell

db.users.drop();

Example: Drop a Collection in Node.js

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

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

dropCollection();

Real-World Use Case

Imagine an e-commerce application where you need to delete orders that have been canceled for over a year.

Example: Deleting Old Orders

async function deleteOldOrders() {
const db = client.db('ecommerce');
const collection = db.collection('orders');

const result = await collection.deleteMany({
status: 'canceled',
canceledAt: { $lt: new Date(new Date().setFullYear(new Date().getFullYear() - 1)) }
});
console.log('Deleted old canceled orders:', result.deletedCount);
}

deleteOldOrders();

Leave a Comment

BoxofLearn