8. Deleting documents
The last basic operation is deleting documents. Use it with caution.
Deleting a document
To delete a single document use deleteOne:
// Deletes the first listing that matches
db.listings.deleteOne({ name: "My apartment in Barcelona" })
MongoDB deletes only the first document it finds with that filter.
Deleting multiple documents
To delete all documents that match a filter use deleteMany:
// Deletes all listings in a specific neighborhood
db.listings.deleteMany({ neighbourhood_group_cleansed: "TEST" })
Careful! If you run
deleteMany({})without a filter, you will delete the entire collection.
Verify before deleting
It is good practice to count how many documents will be deleted before running the command:
// First count
db.listings.countDocuments({ price: "$0.00" })
// If you are sure, delete
db.listings.deleteMany({ price: "$0.00" })
Delete vs Drop
There is a difference between deleting documents and deleting the entire collection:
// Deletes ALL documents (but keeps the collection)
db.listings.deleteMany({})
// Deletes the ENTIRE collection (including indexes)
db.listings.drop()
Using drop() is faster if you want to delete everything, but it also removes any indexes you have created.
It cannot be undone
Deletions are permanent. MongoDB does not have an "undo" command. That is why it is important to:
- Make regular backups
- Test your filters with
find()before usingdeleteMany() - Use
deleteOne()when you only want to delete a single document
Activity 1
Warning: These operations delete data permanently. Work carefully.
- Insert a test listing with your name in the
namefield - Delete that listing using
deleteOne() - Insert 3 test listings with the neighborhood "TEST"
- Count how many documents there are with the neighborhood "TEST"
- Delete all listings in the "TEST" neighborhood using
deleteMany()
Pro:
- Create a new collection called
temporaland insert 10 documents - Delete the first 5 documents using
deleteMany()with an appropriate filter - Delete the entire collection using
drop()and verify that it no longer exists withshow collections
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.