Delete MongoDB Data

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to effectively delete data in a MongoDB database. You will start by deleting a single document, then explore techniques for performing bulk deletions and removing data based on specific conditions. Finally, you will learn how to clear an entire collection and verify the deletion results. These skills are essential for managing your MongoDB database and maintaining data integrity.

The lab covers the following steps: Delete Single Document, Perform Bulk Deletes, Remove By Conditions, Clear Collection Data, and Verify Deletion Results. By the end of this lab, you will have a solid understanding of how to delete data in MongoDB using various methods to suit your needs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/QueryOperationsGroup(["`Query Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/AggregationOperationsGroup(["`Aggregation Operations`"]) mongodb/BasicOperationsGroup -.-> mongodb/start_mongodb_shell("`Start MongoDB Shell`") mongodb/BasicOperationsGroup -.-> mongodb/delete_document("`Delete Document`") mongodb/BasicOperationsGroup -.-> mongodb/bulk_delete_documents("`Bulk Delete Documents`") mongodb/QueryOperationsGroup -.-> mongodb/find_documents("`Find Documents`") mongodb/QueryOperationsGroup -.-> mongodb/query_with_conditions("`Query with Conditions`") mongodb/AggregationOperationsGroup -.-> mongodb/aggregate_group_totals("`Aggregate Group Totals`") subgraph Lab Skills mongodb/start_mongodb_shell -.-> lab-420822{{"`Delete MongoDB Data`"}} mongodb/delete_document -.-> lab-420822{{"`Delete MongoDB Data`"}} mongodb/bulk_delete_documents -.-> lab-420822{{"`Delete MongoDB Data`"}} mongodb/find_documents -.-> lab-420822{{"`Delete MongoDB Data`"}} mongodb/query_with_conditions -.-> lab-420822{{"`Delete MongoDB Data`"}} mongodb/aggregate_group_totals -.-> lab-420822{{"`Delete MongoDB Data`"}} end

Delete Single Document

In this step, we'll learn how to delete a single document in MongoDB using the deleteOne() method. First, launch the MongoDB shell:

mongosh

Let's create a sample collection with some documents to practice deletion:

use mylab_database
db.users.insertMany([
    { name: "John Doe", age: 30, email: "[email protected]" },
    { name: "Jane Smith", age: 25, email: "[email protected]" },
    { name: "Bob Johnson", age: 35, email: "[email protected]" }
])

Example output:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("..."),
    '2': ObjectId("...")
  }
}

To delete a single document, we'll use the deleteOne() method. This method allows you to remove a specific document based on a unique identifier or a specific condition:

db.users.deleteOne({ name: "Jane Smith" })

Expected output:

{ acknowledged: true, deletedCount: 1 }

Let's break down the command:

  • deleteOne() removes only the first document that matches the specified criteria
  • If multiple documents match, only the first one is deleted
  • The method returns an object with acknowledged (operation success) and deletedCount (number of documents deleted)

Verify the deletion by finding all users:

db.users.find()

Expected output will show only two documents for John Doe and Bob Johnson.

Perform Bulk Deletes

In this step, we'll explore how to delete multiple documents at once using the deleteMany() method in MongoDB.

Let's create some sample data:

use mylab_database
db.users.insertMany([
    { name: "Alice Wilson", age: 28, status: "inactive" },
    { name: "Charlie Brown", age: 40, status: "inactive" },
    { name: "David Lee", age: 35, status: "active" },
    { name: "Eve Taylor", age: 45, status: "inactive" }
])

Example output:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("..."),
    '2': ObjectId("..."),
    '3': ObjectId("...")
  }
}

Now, use deleteMany() to remove all users with the "inactive" status:

db.users.deleteMany({ status: "inactive" })

Expected output:

{ acknowledged: true, deletedCount: 3 }

Key points about deleteMany():

  • Removes all documents matching the specified criteria
  • Returns the total number of documents deleted
  • Provides an efficient way to remove multiple records simultaneously

Verify the remaining documents:

db.users.find()

Expected output will show only the active users in the collection.

Remove By Conditions

In this step, we'll learn how to delete documents using complex conditions in MongoDB.

Create a sample collection:

use mylab_database
db.employees.insertMany([
    { name: "John Doe", age: 25, department: "Sales", salary: 50000 },
    { name: "Jane Smith", age: 35, department: "Marketing", salary: 60000 },
    { name: "Bob Johnson", age: 45, department: "Sales", salary: 55000 },
    { name: "Alice Brown", age: 30, department: "HR", salary: 52000 }
])

Example output:

{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("..."),
    '1': ObjectId("..."),
    '2': ObjectId("..."),
    '3': ObjectId("...")
  }
}
  1. Remove employees older than 40:
db.employees.deleteMany({ age: { $gt: 40 } })

Expected output:

{ acknowledged: true, deletedCount: 1 }

Explanation:

  • $gt operator means "greater than"
  • This command deletes documents where age is greater than 40
  1. Remove employees from Sales department with salary less than 55000:
db.employees.deleteMany({
    department: "Sales",
    salary: { $lt: 55000 }
})

Expected output:

{ acknowledged: true, deletedCount: 1 }

Explanation:

  • $lt means "less than"
  • Deletes documents matching both department and salary conditions

Verify remaining documents:

db.employees.find()

Clear Collection Data

In this step, we'll explore methods to completely clear data from a MongoDB collection.

Create a sample collection:

use mylab_database
db.products.insertMany([
  { name: "Laptop", price: 1000, category: "Electronics" },
  { name: "Smartphone", price: 500, category: "Electronics" },
  { name: "Headphones", price: 100, category: "Electronics" }
])

Method 1: Remove All Documents Using deleteMany():

db.products.deleteMany({})

Expected output:

{ acknowledged: true, deletedCount: 3 }

Explanation:

  • Removes all documents without deleting the collection structure
  • Empty filter {} targets all documents

Verify the collection is empty:

db.products.find()

Method 2: Drop the Entire Collection Using drop():

db.products.drop()

Expected output:

true

Explanation:

  • Completely removes the collection and its metadata
  • Permanent deletion of the entire collection

Attempt to find the collection:

db.products.find()

This will result in an error indicating the collection no longer exists.

Verify Deletion Results

In this final step, we'll explore techniques to verify deletion operations in MongoDB.

Create a sample collection:

use mylab_database
db.employees.insertMany([
    { name: "Alice", department: "HR", salary: 50000 },
    { name: "Bob", department: "Sales", salary: 45000 },
    { name: "Charlie", department: "Marketing", salary: 55000 },
    { name: "David", department: "Sales", salary: 40000 }
])
  1. Remove low-salary employees and verify:
db.employees.deleteMany({ salary: { $lt: 45000 } })
const remainingEmployees = db.employees.countDocuments()
print("Remaining employees:", remainingEmployees)

Expected output:

Remaining employees: 3
  1. Verify Deletion Using find():
const lowSalaryEmployees = db.employees.find({ salary: { $lt: 45000 } }).count()
print("Low salary employees after deletion:", lowSalaryEmployees)

Expected output:

Low salary employees after deletion: 0
  1. Check Specific Department Counts:
const salesEmployees = db.employees.countDocuments({ department: "Sales" })
print("Sales department employees:", salesEmployees)

Expected output:

Sales department employees: 1

Comprehensive Verification:

print("Total employees:", db.employees.countDocuments())
print("Employees by department:")
db.employees.aggregate([
    { $group: { _id: "$department", count: { $sum: 1 } } }
])

Expected output will show total employee count and breakdown by department.

Summary

In this lab, you learned how to delete single documents using the deleteOne() method, which removes the first document that matches the specified criteria. You also explored performing bulk deletes with the deleteMany() method, which allows you to efficiently remove multiple records that match specific conditions. Additionally, you learned how to remove documents by conditions, clear an entire collection's data, and verify the deletion results.

The key takeaways from this lab are the different approaches to deleting data in MongoDB, from removing individual documents to performing mass deletions based on specific criteria. These skills are essential for effectively managing your database and maintaining data integrity.

Other MongoDB Tutorials you may like