Lesson 5
Deleting Documents in MongoDB
Introduction

Hello there! This lesson covers an essential aspect of working with MongoDB: deleting documents from MongoDB collections. The ability to remove data from your database is crucial for various reasons such as removing outdated or incorrect data. Let’s explore MongoDB’s data deletion mechanisms.

Two Ways to Delete Data

MongoDB offers two primary methods to delete data from collections:

  1. deleteOne(): Deletes a single document that matches the specified filter.

    1db.collection.deleteOne(filter)
  2. deleteMany(): Deletes multiple documents that match the specified filter.

    1db.collection.deleteMany(filter)
Deleting a Single Document

Using the deleteOne() method, you can remove a single document from a collection based on a filter. Here is an example where we delete a book with the title "1984" from the books collection:

JavaScript
1use library_db 2 3db.books.deleteOne({ title: "1984" })

In this example, the command db.books.deleteOne({ title: "1984" }) deletes the first document from the books collection where the title is "1984".

Deleting Multiple Documents

To remove multiple documents at once, the deleteMany() method comes into play. Below is an example that deletes all books of the genre "Fiction" from the books collection:

JavaScript
1use library_db 2 3db.books.deleteMany({ genre: "Fiction" })

In this example, the deleteMany() method is used to delete all documents where the genre is "Fiction". This command removes all books of the "Fiction" genre from the books collection.

Summary

In this lesson, we covered the basics of deleting data from MongoDB collections. You learned how to use the deleteOne() method to delete a single document and the deleteMany() method to delete multiple documents. These operations are essential for maintaining and managing your database correctly. Get ready to practice these concepts in the upcoming exercises!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.