Delete Documents
mongo --host 127.0.0.1:27017
The examples on this page use the inventory collection. To populate the inventory collection, run the following:
db.inventory.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 10 }
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
] );
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5b56d0e5e68eb0362ce719bc"),
ObjectId("5b56d0e5e68eb0362ce719bd"),
ObjectId("5b56d0e5e68eb0362ce719be"),
ObjectId("5b56d0e5e68eb0362ce719bf"),
ObjectId("5b56d0e5e68eb0362ce719c0")
]
}
Delete Methods
Delete All Documents
To delete all documents from a collection, pass an empty filter document {} to the db.collection.deleteMany() method.
db.inventory.deleteMany({})
{ "acknowledged" : true, "deletedCount" : 5 }
Populate the inventory collection
db.inventory.insertMany( [
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
] );
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5b56d156e68eb0362ce719c1"),
ObjectId("5b56d156e68eb0362ce719c2"),
ObjectId("5b56d156e68eb0362ce719c3"),
ObjectId("5b56d156e68eb0362ce719c4"),
ObjectId("5b56d156e68eb0362ce719c5")
]
}
Delete All Documents that Match a Condition
The following example removes all documents from the inventory collection where the status field equals "A":
db.inventory.deleteMany({ status : "A" })
{ "acknowledged" : true, "deletedCount" : 2 }
Delete Only One Document that Matches a Condition
The following example deletes the first document where status is "D":
db.inventory.deleteOne( { status: "D" } )
{ "acknowledged" : true, "deletedCount" : 1 }
Delete Behavior
Indexes
Delete operations do not drop indexes, even if deleting all documents from a collection.
Atomicity
All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.
Write Acknowledgement
With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.