Delete

In this lab, we examine the MongoDB methods using for deleting documents from a collection.

db.collection.remove()

Removes documents from a collection. The remove() method can take a query document and an optional justOne boolean:

db.collection.remove(
   <query>,
   <justOne>
)

remove() example

The following example removes all documents in a collection. The remove method is called with an empty query document {}. The following operation deletes all documents from the bios collection:

db.bios.remove( { } )

This operation is not equivalent to the drop() method.

drop() example

To remove all documents from a collection, it may be more efficient to use the drop() method to drop the entire collection, including the indexes, and then recreate the collection and rebuild the indexes.

The following operation drops the students collection in the current database.

db.students.drop()

Setting conditions and options

Remove All Documents that Match a Condition

To remove the documents that match a deletion criteria, call the remove() method with the parameter. The following operation removes all the documents from the collection products where qty is greater than 20:

db.products.remove( { qty: { $gt: 20 } } )

All of the operators covered in the find() section can also be used in the remove query (gt, lt, eq, in, etc.)

Remove a Single Document that Matches a Condition

To remove the first document that matches a deletion criteria, call the remove method with the query criteria and the justOne parameter set to true or 1.

The following operation removes only the first document from the collection products where qty is greater than 20:

db.products.remove( { qty: { $gt: 20 } }, true )

Exercises

Perform the following deletes on your grades collection.

  1. Remove the document that relates to student 9 and class 15.
  2. Remove all of the documents belonging to student 19.
  3. Use a find() query to show all documents with an exam score of less than or equal to 5. Then, use remove() to delete the first of these documents (hint: you need to set the justOne option).

Further reading

  • Use deleteOne() to delete a single document from the grades collection.
  • Use deleteMany() to delete multiple documents.
  • Use find() after your deletes to confirm that the documents have been removed.

Solutions

Solutions for the exercises in this lab are available here: delete_solutions.zip