MongoDB - Delete Document
MongoDB - Deleting Documents
Section titled “MongoDB - Deleting Documents”This chapter covers the modern, recommended methods for deleting documents from a MongoDB collection: deleteOne() and deleteMany(). The older remove() method is now deprecated and should be avoided in new applications.
The deleteOne() Method
Section titled “The deleteOne() Method”Use deleteOne() to delete at most one document that matches the specified filter, even if multiple documents match. It will delete the first matching document it finds.
Syntax
Section titled “Syntax”db.COLLECTION_NAME.deleteOne(<filter>, <options>)Example
Section titled “Example”Consider a shoppingCart collection. Let’s remove a specific item, ‘apples’, for a user.
// Sample Data:db.shoppingCart.insertMany([ { userId: "user123", item: "apples", quantity: 2 }, { userId: "user123", item: "bread", quantity: 1 }, { userId: "user456", item: "apples", quantity: 3 }]);
// Delete the 'apples' document for 'user123'db.shoppingCart.deleteOne({ userId: "user123", item: "apples" });The operation returns a document confirming the result:
{ "acknowledged": true, "deletedCount": 1}If no document matches the filter, deletedCount will be 0.
The deleteMany() Method
Section titled “The deleteMany() Method”Use deleteMany() to delete all documents that match the specified filter.
Syntax
Section titled “Syntax”db.COLLECTION_NAME.deleteMany(<filter>, <options>)Example
Section titled “Example”Let’s say we want to clear the entire shopping cart for ‘user123’.
// Delete all documents for 'user123'db.shoppingCart.deleteMany({ userId: "user123" });
// Result:{ "acknowledged": true, "deletedCount": 2 // Both 'apples' and 'bread' were deleted}Security Best Practice: The Danger of an Empty Filter
Section titled “Security Best Practice: The Danger of an Empty Filter”Passing an empty filter document {} to deleteMany() will delete all documents in the collection. This is a destructive and often irreversible action.
// DANGER: This will delete every document in the shoppingCart collection!db.shoppingCart.deleteMany({});Always double-check your filters before executing a deleteMany command. If your goal is to drop the entire collection and its indexes, it’s more efficient to use db.collection.drop().
[Deprecated] The remove() Method
Section titled “[Deprecated] The remove() Method”The db.collection.remove() method is deprecated as of MongoDB v3.2. Modern drivers and the mongo shell will issue a warning if you use it. You should update any existing code to use deleteOne() or deleteMany() for clarity and to align with modern best practices.