delete
The `delete` command is used to remove documents from a collection. A single document or multiple documents can be deleted based on a specified query filter.
Deletes documents from a collection that match the specified filter criteria.
Syntax
db.collection.deleteOne(
<filter>,
<options>
);
db.collection.deleteMany(
<filter>,
<options>
);
Parameters
filter
objectrequiredA document that specifies the criteria for deletion. Only the documents that match the filter are deleted.
options
objectA document that specifies options for the delete operation. Common options include writeConcern and collation.
Examples
Sample Data
{
"_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
"name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
"location": {
"lat": -89.2384,
"lon": -46.4012
},
"staff": {
"totalStaff": {
"fullTime": 8,
"partTime": 20
}
},
"sales": {
"totalSales": 75670,
"salesByCategory": [
{
"categoryName": "Wine Accessories",
"totalSales": 34440
},
{
"categoryName": "Bitters",
"totalSales": 39496
},
{
"categoryName": "Rum",
"totalSales": 1734
}
]
},
"promotionEvents": [
{
"eventName": "Unbeatable Bargain Bash",
"discounts": [
{
"categoryName": "Whiskey",
"discountPercentage": 7
}
]
}
]
}
Delete all documents in a collection
Use `deleteMany` with an empty filter to delete all documents in a collection.
This command removes every document from the stores collection.
Query:
db.stores.deleteMany({})
Output:
{ acknowledged: true, deletedCount: 60570 }
Delete a document that matches a specified query filter
Use `deleteOne` to remove a single document that matches the filter.
This command deletes the document with the specified `_id` value.
Query:
db.stores.deleteOne({"_id": "68471088-4d45-4164-ae58-a9428d12f310"})
Output:
{ acknowledged: true, deletedCount: 1 }
Delete all documents that match a specified query filter
Use `deleteMany` to remove all documents matching the filter criteria.
This command deletes all documents where the discount percentage is 21.
Query:
db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 0})
Output:
{ acknowledged: true, deletedCount: 142 }
Delete only one of many documents that match a specified query filter
Use `deleteMany` with a limit of 1 to delete only one matching document.
This command deletes just one document where the discount percentage is 21.
Query:
db.stores.deleteMany({"promotionEvents.discounts.discountPercentage": 21}, {"limit": 1})
Output:
{ acknowledged: true, deletedCount: 1 }