Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách tạo nhiều index cùng lúc trong MongoDB

Giới thiệu

Để tạo nhiều index cùng một lúc (batch), MongoDB cung cấp phương thức createIndexes() nhận một mảng các specification index. Điều này hiệu quả hơn việc gọi createIndex() nhiều lần.

Cú pháp

db.tenCollection.createIndexes([
    { "truong1": 1 },
    { "truong2": -1 },
    { "truong3": 1, "truong4": -1 },  // Compound index
    { "truong5": "text" },            // Text index
    { "location": "2dsphere" }        // Geospatial index
]);

Ví dụ minh họa

1. Tạo 5 index đơn lẻ cùng lúc

> db.nhieuIndexDemo.createIndexes([
    { "First": 1 },
    { "Second": 1 },
    { "Third": 1 },
    { "Fourth": 1 },
    { "Fifth": 1 }
]);

2. Kết quả

{ 
    "createdCollectionAutomatically" : true, 
    "numIndexesBefore" : 1, 
    "numIndexesAfter" : 6, 
    "ok" : 1 
}

(1 index mặc định _id + 5 index mới = 6 total)

3. Xem tất cả index

> db.nhieuIndexDemo.getIndexes();
[
    { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.nhieuIndexDemo" },
    { "v" : 2, "key" : { "First" : 1 }, "name" : "First_1", "ns" : "test.nhieuIndexDemo" },
    { "v" : 2, "key" : { "Second" : 1 }, "name" : "Second_1", "ns" : "test.nhieuIndexDemo" },
    { "v" : 2, "key" : { "Third" : 1 }, "name" : "Third_1", "ns" : "test.nhieuIndexDemo" },
    { "v" : 2, "key" : { "Fourth" : 1 }, "name" : "Fourth_1", "ns" : "test.nhieuIndexDemo" },
    { "v" : 2, "key" : { "Fifth" : 1 }, "name" : "Fifth_1", "ns" : "test.nhieuIndexDemo" }
]

Các tùy chọn index phổ biến

db.collection.createIndexes([
    // Unique index
    { key: { "email": 1 }, unique: true, name: "email_unique" },
    
    // Sparse index (chỉ index doc có field này)
    { key: { "optionalField": 1 }, sparse: true, name: "optionalField_sparse" },
    
    // TTL index (tự động xóa sau thời gian)
    { key: { "createdAt": 1 }, expireAfterSeconds: 3600, name: "ttl_1h" },
    
    // Partial index (chỉ index doc thỏa filter)
    { key: { "status": 1 }, partialFilterExpression: { status: "active" }, name: "status_active" },
    
    // Collation (cho text search có locale)
    { key: { "name": 1 }, collation: { locale: "vi", strength: 2 }, name: "name_vi" }
]);

Lợi ích của createIndexes() batch

  • **Atomic**: Tất cả thành công hoặc tất cả thất bại (rollback)
  • **Hiệu quả**: Chỉ quét collection một lần để build tất cả index
  • **Khóa ít hơn**: Giảm thời gian lock so với tạo lần lượt
  • **Dễ quản lý**: Deploy schema changes trong một lần

Lưu ý

  • Tên index tự động tạo: "field_1" hoặc "field_1_field2_-1"
  • Đặt tên tùy chỉnh với option name để dễ quản lý
  • Giới hạn: tối đa 64 index trên một collection
  • Index build foreground (mặc định) block write - dùng background: true cho production (deprecated trong 4.2+, dùng rolling build)

Xóa nhiều index cùng lúc

// Xóa tất cả index trừ _id
db.collection.dropIndexes();

// Xóa index cụ thể theo tên
db.collection.dropIndex("First_1");
db.collection.dropIndex("email_unique");