如何強制 MongoDB 使用 BasicCursor 而不是索引?


為避免使用索引,請在 MongoDB 中使用 hint()。讓我們建立一個帶有文件的集合 −

> 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")
}

使用 find() 方法顯示集合中的所有文件 −

> db.demo31.find();

這將生成以下輸出 −

{ "_id" : ObjectId("5e174f8fcfb11e5c34d898c1"), "StudentFirstName" : "John" }
{ "_id" : ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName" : "Jace" }
{ "_id" : ObjectId("5e174f9ccfb11e5c34d898c3"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName" : "James" }

以下是對 BasicCursor 代替索引的 MongoDB 強制查詢 −

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

這將生成以下輸出 −

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

更新於: 02-04-2020

150 次檢視

職業生涯快速啟動

完成課程即可獲得認證

開始
廣告
© . All rights reserved.