Để xóa toàn bộ index (trừ _id) của tất cả collection trong database hiện tại, dùng getCollectionNames() lặp qua và chạy dropIndexes.
Cú pháp:
db.getCollectionNames().forEach(function(collName) {
db.runCommand({ dropIndexes: collName, index: "*" });
});
Ví dụ kiểm tra trước/sau:
Trước khi xóa - collection indexingDemo có 2 index:
> db.indexingDemo.getIndexes();
[
{ "v": 2, "key": { "_id": 1 }, "name": "_id_", "ns": "test.indexingDemo" },
{ "v": 2, "key": { "StudentFavouriteSubject": 1 }, "name": "StudentFavouriteSubject_1", "ns": "test.indexingDemo", "background": true }
]
Chạy lệnh xóa:
> db.getCollectionNames().forEach(function(allCollectionName) {
db.runCommand({ dropIndexes: allCollectionName, index: "*" });
});
Sau khi xóa - chỉ còn index _id:
> db.indexingDemo.getIndexes();
[
{ "v": 2, "key": { "_id": 1 }, "name": "_id_", "ns": "test.indexingDemo" }
]
Lưu ý:
- Index
_idkhông thể xóa (bắt buộc). - Lệnh này xóa index trên tất cả collection trong database hiện tại.
- Cẩn thận khi chạy trên production - có thể ảnh hưởng hiệu năng truy vấn.