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.
MongoDB offers two primary methods to delete data from collections:
-
deleteOne(): Deletes a single document that matches the specified filter.
1db.collection.deleteOne(filter)
-
deleteMany(): Deletes multiple documents that match the specified filter.
1db.collection.deleteMany(filter)
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:
JavaScript1use 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".
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:
JavaScript1use 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.
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!