Sử dụng lệnh reIndex() để xóa và tạo lại tất cả index trên collection (trừ _id). Hữu ích khi index bị fragmentation hoặc thống kê lỗi thời.
Tạo index:
> db.demo42.createIndex({"StudentFirstName":1});
Tái xây dựng index:
> db.demo42.reIndex({"StudentFirstName":1});Kết quả (thông tin index sau rebuild):
Khi nào nên reIndex:
- Index bị phân mảnh (fragmentation) sau nhiều insert/update/delete
- Thống kê index lỗi thời gây query planner chọn sai plan
- Sau khi khôi phục từ backup
- Thay đổi collation
⚠️ Cảnh báo:
reIndex()**khóa collection** (blocking) - chỉ chạy trong maintenance window- Trên replica set: chạy trên secondary trước, sau đó step down primary
- MongoDB 4.2+: dùng
reIndexcommand hoặcdb.collection.reIndex() - Thường không cần thiết nếu dùng WiredTiger (tự compact)
Thay thế nhẹ nhàng hơn: db.collection.reIndex() hoặc drop/create index riêng lẻ.