Để xóa tất cả các document (record) trong một collection MongoDB, bạn sử dụng phương thức remove() với query rỗng.
Cú pháp
db.yourCollectionName.remove({});
Ví dụ minh họa
Tạo collection và dữ liệu
> db.deleteAllRecordsDemo.insertOne({"StudentName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f6ca32f684a30fbdfd596") }
> db.deleteAllRecordsDemo.insertOne({"StudentName":"Carol","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f6cb22f684a30fbdfd597") }
> db.deleteAllRecordsDemo.insertOne({"StudentName":"Mike","StudentAge":23,"Hobby":["Learning","Photography"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8f6cde2f684a30fbdfd598") }
Xem dữ liệu ban đầu
> db.deleteAllRecordsDemo.find().pretty();
{
"_id" : ObjectId("5c8f6ca32f684a30fbdfd596"),
"StudentName" : "John"
}
{
"_id" : ObjectId("5c8f6cb22f684a30fbdfd597"),
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c8f6cde2f684a30fbdfd598"),
"StudentName" : "Mike",
"StudentAge" : 23,
"Hobby" : [ "Learning", "Photography" ]
}
Xóa tất cả records
> db.deleteAllRecordsDemo.remove({});
WriteResult({ "nRemoved" : 3 })
nRemoved: 3 xác nhận 3 document đã bị xóa.
Kiểm tra sau khi xóa
> db.deleteAllRecordsDemo.find().pretty();
>
Không còn document nào.
Lưu ý quan trọng
Cảnh báo:
remove({}) xóa vĩnh viễn tất cả document trong collection. Hành động này không thể hoàn tác.
Phương thức thay thế (MongoDB 3.2+)
Khuyến khích dùng deleteMany() thay cho remove():
// Xóa tất cả document
db.collection.deleteMany({});
// Xóa với điều kiện
db.collection.deleteMany({ status: "inactive" });
So sánh remove() vs deleteMany()
| Đặc điểm | remove() | deleteMany() |
|---|---|---|
| Trả về | WriteResult | DeleteResult (có deletedCount) |
| Hỗ trợ write concern | Có | Có |
| Collation support | Không | Có |
| Deprecated | Có (từ 3.2) | Không |
Xóa collection hoàn toàn (bao gồm indexes)
db.collection.drop()
Nhanh hơn remove/deleteMany vì chỉ xóa metadata, không quét document.