索引可以加快速度讀取,在寫入、刪除、更新的時候,會受到影響,因爲在執行操作的時候,它們都會去讀取索引,實際應用中有時候爲了加快訪問速度, 犧牲掉增刪改的一點性能,還是有必要的,具體選擇,根據實際使用業務場景,建立合適的索引。
// 添加索引
db.collection.createIndex({field: true})
// 未添加索引之前,會掃描整個集合, 顯示COLLSCAN表示一組掃描,顯示IXSCAN指示索引使用。
//explain() 查詢分析器, 下面type未加索引
db.inventory.find({type:'food'}).explain();
結果如下:
db.inventory.find({type:'food'}).explain();
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "MyDB.inventory",
"indexFilterSet" : false,
"parsedQuery" : {
"type" : {
"$eq" : "food"
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"type" : {
"$eq" : "food"
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "DESKTOP-U0M7P28",
"port" : 27017,
"version" : "3.2.10",
"gitVersion" : "79d9b3ab5ce20f51c272b4411202710a082d0317"
},
"ok" : 1
}
給type字段創建一個索引
db.inventory.createIndex({ type: true })
// 在使用查詢語句
db.inventory.find({ type : 'food'}).explain()
// 分析結果
db.inventory.find({ type : 'food'}).explain();
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "MyDB.inventory",
"indexFilterSet" : false,
"parsedQuery" : {
"type" : {
"$eq" : "food"
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"type" : true
},
"indexName" : "type_true",
"isMultiKey" : false,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "forward",
"indexBounds" : {
"type" : [
"[\"food\", \"food\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "DESKTOP-U0M7P28",
"port" : 27017,
"version" : "3.2.10",
"gitVersion" : "79d9b3ab5ce20f51c272b4411202710a082d0317"
},
"ok" : 1
}