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

Buộc MongoDB dùng BasicCursor thay vì index với hint()

Để buộc MongoDB không sử dụng index mà quét toàn bộ collection (collection scan), dùng phương thức hint() với {$natural: 1}.

Tạo collection và index:

> db.demo31.createIndex({"StudentFirstName":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo31.insertOne({"StudentFirstName":"John"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e174f8fcfb11e5c34d898c1") }
> db.demo31.insertOne({"StudentFirstName":"Jace"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e174f97cfb11e5c34d898c2") }
> db.demo31.insertOne({"StudentFirstName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e174f9ccfb11e5c34d898c3") }
> db.demo31.insertOne({"StudentFirstName":"James"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e174fa0cfb11e5c34d898c4") }

Xem dữ liệu:

> db.demo31.find();
{ "_id" : ObjectId("5e174f8fcfb11e5c34d898c1"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName" : "Jace" }
{ "_id" : ObjectId("5e174f9ccfb11e5c34d898c3"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName" : "James" }

Buộc dùng BasicCursor (collection scan) với regex:

> db.demo31.find({"StudentFirstName": {$regex: '^Ja'}}).hint({$natural: 1});

Kết quả (Jace, James):

{ "_id" : ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName" : "Jace" }
{ "_id" : ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName" : "James" }

Khi nào dùng hint():

  • Kiểm tra hiệu năng: so sánh index scan vs collection scan
  • Index không tối ưu cho truy vấn cụ thể
  • Debug execution plan với explain()

Lưu ý: hint() chỉ áp dụng cho truy vấn hiện tại. Index vẫn tồn tại cho các truy vấn khác.