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
- deleteOne: Deletes a single document matching the specified condition.
- deleteMany: Deletes multiple documents that match the given condition.
- Flexible Conditions: Use query operators for precise deletion.
- Permanent Deletion: Deleted documents cannot be recovered unless backed up.
Prerequisites
- MongoDB Installed: Download MongoDB from mongodb.com.
- Node.js Installed: Download and install Node.js from nodejs.org.
- 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
- Launch MongoDB Compass and connect to your MongoDB server (mongodb://localhost:27017).
- Select your database and collection.
Step 2: Delete Documents
- Filter documents using the query box, e.g., { age: { $gt: 30 } }.
- 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();