This chapter introduces how to delete MongoDB documents using the mongo shell.
Prepare test data
Insert a batch of test data into the insertMany 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" },
] );
Delete all documents
Delete all documents in the inventory collection.
db.inventory.deleteMany({})
Here, an empty query condition {} is passed in.
Delete a batch of documents based on a condition
db.inventory.deleteMany({ status: "A" })
Explanation:
- Delete documents in the inventory collection where the status field matches "A".
- The deleteMany function supports query conditions.
Delete a single document based on a condition
db.inventory.deleteOne( { status: "D" } )
Explanation:
- Delete the first document in the inventory collection where the status field matches "D".