In this lab, we examine the MongoDB methods using for deleting documents from a collection.
Removes documents from a collection. The remove() method can take a query document and an optional justOne boolean:
db.collection.remove(
<query>,
<justOne>
)
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.
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()
To remove the documents that match a deletion criteria, call the remove() method with the
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.)
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 )
Perform the following deletes on your grades collection.
Examine the deleteOne() and deleteMany() methods in the MongoDB reference:
Solutions for the exercises in this lab are available here: delete_solutions.zip