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:

  1. Make regular backups
  2. Test your filters with find() before using deleteMany()
  3. Use deleteOne() when you only want to delete a single document
Activity 1

Warning: These operations delete data permanently. Work carefully.

  1. Insert a test listing with your name in the name field
  2. Delete that listing using deleteOne()
  3. Insert 3 test listings with the neighborhood "TEST"
  4. Count how many documents there are with the neighborhood "TEST"
  5. Delete all listings in the "TEST" neighborhood using deleteMany()

Pro:

  1. Create a new collection called temporal and insert 10 documents
  2. Delete the first 5 documents using deleteMany() with an appropriate filter
  3. Delete the entire collection using drop() and verify that it no longer exists with show collections

Solutions

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

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 book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.