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

Tạo index nền (background) trong MongoDB

Để tạo index không khóa ghi (non-blocking), dùng createIndex() với {background: true}. Cú pháp:

db.yourCollection.createIndex({"field1":1,"field2":1}, {background: true});

Ví dụ tạo index compound trên StudentName và StudentAge nền:

> db.indexCreationDemo.createIndex({"StudentName":1,"StudentAge":1}, {background: true});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

Kiểm tra các index:

> db.indexCreationDemo.getIndexes();

Kết quả - index mới có "background": true:

Lưu ý: Từ MongoDB 4.2, tất cả index đều tạo nền mặc định, tùy chọn background đã deprecated. Index nền cho phép đọc/ghi tiếp tục trong khi xây dựng, nhưng mất thời gian lâu hơn và tốn tài nguyên hơn.