MongoDB: Deleting Documents
Subject: nodejs
MongoDB: Deleting Documents
Deleting documents in MongoDB removes existing records from a collection. This operation is critical for managing storage, compliance, and application functionality.
Why Delete Documents?
- Data Lifecycle Management: Remove expired or irrelevant data.
- Compliance: Satisfy legal regulations like GDPR or CCPA.
- Storage Optimization: Free up disk space.
- Application Logic: Allow users or systems to delete specific content.
Core Concepts
- Query Filter: Specifies which documents to delete (e.g.,
{ status: "inactive" }). An empty filter{}matches all documents. - Write Result: Contains metadata like
deletedCount, indicating how many documents were removed.
Node.js Examples: Deleting Documents
Sample Data (customers collection):
1. Delete One Document
Delete the document where name is "Company A".
Expected Output:
2. Delete Many Documents
Delete all documents with status equal to "inactive".
Expected Output:
3. Delete All Documents (deleteMany({}))
Output Example:
4. Drop Entire Collection
Use .drop() to delete all documents and the collection structure itself.
Expected Output:
Key Takeaways
- Use
deleteOne()to remove a single matching document. - Use
deleteMany()to remove all documents matching a filter or everything with{}. - Use
.drop()to remove the entire collection and its indexes. - Deletion is irreversible. Always validate filters before execution.