Delete MongoDB Data

MongoDBBeginner
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 topics: deleting a single document with deleteOne(), removing multiple documents with deleteMany(), using query operators for conditional deletion, and clearing a collection with deleteMany({}) or drop(). By the end of this lab, you will have a solid understanding of how to delete data in MongoDB using various methods.

Delete a Single Document

In this step, you will learn how to delete a single document from a MongoDB collection. First, you need to connect to the MongoDB shell and prepare some sample data.

Launch the MongoDB shell by running the following command in your terminal:

mongosh

Once inside the shell, you will create a new database and a collection with a few documents.

use mylab_database

Create a new collection with a few documents.

db.users.insertMany([
  { name: "John Doe", age: 30, email: "john@example.com" },
  { name: "Jane Smith", age: 25, email: "jane@example.com" },
  { name: "Bob Johnson", age: 35, email: "bob@example.com" }
]);

The output confirms that three documents have been inserted.

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

Now, to delete a single document, use the deleteOne() method. This method finds the first document that matches the specified filter and removes it. Let's delete the document for "Jane Smith".

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

The output indicates that one document was successfully deleted.

{ "acknowledged": true, "deletedCount": 1 }
  • deleteOne(): This method removes only the first document that matches the filter criteria.
  • { name: "Jane Smith" }: This is the filter that specifies which document to delete.
  • deletedCount: 1: This confirms that one document was removed.

To verify that the document has been deleted, you can list all remaining documents in the users collection.

db.users.find();

The output will now show only two documents, confirming that "Jane Smith" has been removed.

Delete Multiple Documents

In the previous step, you deleted a single document. Now, you will learn how to delete multiple documents at once using the deleteMany() method. This is useful for bulk removal operations, such as cleaning up records with a specific status.

First, let's add some new documents to our users collection. These documents will have a status field, which we will use for our bulk delete operation.

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" }
]);

The output will confirm the insertion of four new documents.

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

Now, use the deleteMany() method to remove all users whose status is "inactive".

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

The output shows that three documents were deleted.

{ "acknowledged": true, "deletedCount": 3 }
  • deleteMany(): This method removes all documents that match the filter criteria.
  • { status: "inactive" }: This filter targets all documents where the status field is "inactive".

To confirm the bulk deletion, list all documents remaining in the collection.

db.users.find();

The output will show only the documents that were not "inactive", demonstrating that the bulk delete was successful.

Delete Documents Using Conditions

MongoDB allows you to use powerful query operators to delete documents based on more complex conditions. In this step, you will learn how to use operators like $gt (greater than) and $lt (less than) to perform conditional deletions.

First, let's create a new collection named employees with some sample data.

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 }
]);

The output will confirm the insertion of four documents.

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

Now, let's perform a conditional delete. We will remove all employees who are older than 40.

db.employees.deleteMany({ age: { $gt: 40 } });

The output indicates that one document was deleted.

{ "acknowledged": true, "deletedCount": 1 }
  • { age: { $gt: 40 } }: This filter uses the $gt operator to select documents where the age field is greater than 40.

Next, let's perform a deletion based on multiple conditions. We will remove employees from the "Sales" department whose salary is less than 55,000.

db.employees.deleteMany({
  department: "Sales",
  salary: { $lt: 55000 }
});

The output confirms that another document was deleted.

{ "acknowledged": true, "deletedCount": 1 }
  • This command combines two conditions: the department must be "Sales" and the salary must be less than 55,000 (using the $lt operator).

To verify the results, view the remaining documents in the employees collection.

db.employees.find();

The output will show only the two employees who did not meet the deletion criteria.

Clear All Data from a Collection

Sometimes you may need to remove all documents from a collection. MongoDB provides two primary ways to achieve this: using deleteMany({}) to remove all documents, or using drop() to remove the entire collection.

First, let's create a new products collection with some sample data.

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 with deleteMany()

You can remove all documents from a collection by passing an empty filter {} to the deleteMany() method. This approach deletes the data but preserves the collection itself, including its indexes.

db.products.deleteMany({});

The output shows that all three documents were deleted.

{ "acknowledged": true, "deletedCount": 3 }

You can verify that the collection is now empty by running a find() query.

db.products.find();

This command will return no documents.

Method 2: Drop the Entire Collection with drop()

The drop() method is more destructive. It completely removes the collection, including all its documents, indexes, and associated metadata.

First, let's re-insert the sample data so we have a collection to drop.

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

Now, drop the products collection entirely.

db.products.drop();

The output true confirms that the collection was successfully dropped.

true

If you now try to query the products collection, it will not return any results because the collection no longer exists.

db.products.find();

This command will produce no output, as the collection is gone. To exit the mongosh shell, you can type exit or press Ctrl+D.

Summary

In this lab, you have learned the fundamental techniques for deleting data in MongoDB. You started by using the deleteOne() method to remove a single document based on a specific filter. You then progressed to bulk deletions with deleteMany(), which efficiently removes multiple documents matching a criterion. You also explored how to use query operators like $gt and $lt to perform more complex, conditional deletions. Finally, you learned two methods for clearing a collection: using deleteMany({}) to remove all documents while keeping the collection structure, and using drop() to permanently remove the entire collection.

These skills are crucial for database administration, allowing you to manage data lifecycle, clean up unnecessary records, and maintain the overall health of your MongoDB database.