deleteOne and deleteMany
deleteOne() removes the first document that matches a filter:
db.movies.deleteOne({ _id: 6 })
db.movies.countDocuments()
Output:
{ acknowledged: true, deletedCount: 1 }
7
The report has one number, deletedCount. The count shows seven movies are left. Deleting by _id is the safest way to delete, because only one document can have that _id.
deleteMany() removes every document that matches:
db.movies.deleteMany({ rating: { $lt: 8 } })
db.movies.countDocuments()
Output:
{ acknowledged: true, deletedCount: 2 }
5
Okja was already gone, so two movies were rated below 8: Dunkirk and First Man. Both were deleted in one call, and five movies are left.
deleteMany({}) deletes every document in the collection. It does not ask you to confirm, and you cannot undo it. Before you delete many documents, run countDocuments with the same filter and check that the number is what you expect.
If nothing matches, delete does not give an error. The report just shows deletedCount: 0.
In the exercise, delete the movie with _id 8.