Giới thiệu
Để xóa hàng loạt collection có tên khớp với một chuỗi ký tự (pattern), bạn có thể lặp qua danh sách collection và dùng drop() trên từng collection khớp điều kiện.
Quy trình thực hiện
1. Xem danh sách collection hiện có
> show collections;
Giả sử database "sample" có các collection:
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteMultipleIdsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
... (các collection khác)
2. Script xóa collection có tên bắt đầu bằng "delete"
> var allCollectionName = db.getCollectionNames();
> for(var j = 0, colLength = allCollectionName.length; j < colLength; j++) {
var colName = allCollectionName[j];
if(colName.indexOf('delete') === 0) {
db[colName].drop();
}
}
3. Kết quả
True
4. Kiểm tra lại danh sách collection
> show collections;
Các collection "delete*" đã bị xóa, các collection còn lại:
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findMimimumElementInArrayDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
insertDocumentWithDateDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
sumTwoFieldsDemo
truncateDemo
updateInformation
userInformation
Cải tiến: Sử dụng regex để linh hoạt hơn
var collections = db.getCollectionNames();
var pattern = /^delete/; // Bắt đầu bằng "delete"
collections.forEach(function(name) {
if (pattern.test(name)) {
print("Dropping: " + name);
db[name].drop();
}
});
⚠️ Cảnh báo quan trọng
- Thao tác không thể hoàn tác - Collection bị xóa vĩnh viễn
- Luôn sao lưu dữ liệu trước khi chạy script xóa hàng loạt
- Test trước với
print(name)thay vìdrop()để xem danh sách sẽ bị xóa - Cân nhắc dùng
db.collection.renameCollection()thay vì xóa nếu muốn giữ dữ liệu
Phương án an toàn hơn: Dùng MongoDB Shell Script
// File: drop_collections.js
var pattern = /^delete/;
var collections = db.getCollectionNames();
var toDrop = collections.filter(function(name) { return pattern.test(name); });
print("Sẽ xóa " + toDrop.length + " collections:");
toDrop.forEach(print);
if (confirm("Tiếp tục?")) {
toDrop.forEach(function(name) { db[name].drop(); });
print("Đã xóa xong.");
}
Chạy: mongo sample drop_collections.js