Trung BìnhMongoDB iconMongoDB

Compound index trong MongoDB cần chọn thứ tự field thế nào?

Compound index order phụ thuộc query shape. Quy tắc thực tế thường là equality fields trước, sort fields tiếp theo, range fields sau cùng. Index { tenantId: 1, status: 1, createdAt: -1 } tốt cho query lọc tenant/status và sort createdAt.

Ví dụ:

javascript
db.orders.createIndex({ tenantId: 1, status: 1, createdAt: -1 })

Không có một thứ tự đúng cho mọi query.

Nếu query khác nhau nhiều, cần cân nhắc index riêng hoặc đổi access pattern.

Xem toàn bộ MongoDB cùng filter theo level & chủ đề con.

Mở danh sách MongoDB