萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

MongoDB 索引完整指南:從基礎操作到進階優化實戰

為什麼需要索引?

索引是資料庫查詢效能的關鍵。當系統執行查詢時,若缺乏適當索引,MongoDB 必須掃描集合中的每一份文件(全集合掃描),這在大量資料下會嚴重拖慢效能。建立索引後,查詢優化器可透過 B-Tree 結構快速定位文件,實現數量級的效能提升。

一、單欄位索引建立與驗證

1. 準備測試資料

for (var i = 0; i < 200000; i++) {
  db.books.insert({ number: i, name: i + "book" })
}

2. 未建索引時的查詢效能

var start = new Date()
db.books.find({ number: 65871 })
var end = new Date()
print(end - start)  // 通常需數十至上百毫秒

3. 建立升序索引

db.books.ensureIndex({ number: 1 })

4. 建索引後再次測試

同樣查詢耗時將降至 0-1 毫秒,效能提升顯著。

二、索引使用的關鍵注意事項

  1. 排序方向:1 為升序,-1 為降序;單欄位索引方向對單向查詢影響不大,但複合索引與排序操作時須謹慎規劃。
  2. 寫入效能權衡:索引加速讀取,但會降低寫入(插入/更新/刪除)速度。適合「讀多寫少」的集合。
  3. 複合索引欄位順序:遵循 ESR 原則(Equality → Sort → Range),優先放置等值查詢欄位。
  4. 非萬能藥:並非每個欄位都需索引;過多索引會佔用記憶體並拖慢寫入。
  5. 排序優化:大量資料排序時,若有對應索引可避免記憶體內排序,提升效能。

三、指定索引名稱

db.books.ensureIndex({ name: -1 }, { name: "bookname" })

自訂名稱便於後續管理與識別。

四、唯一索引:防止重複值

1. 建立唯一索引

db.books.ensureIndex({ name: -1 }, { unique: true })

2. 測試插入重複值

db.books.insert({ name: "1book" })  // 第一次成功
db.books.insert({ name: "1book" })  // 拋出 E11000 duplicate key 錯誤

五、建立唯一索引時剔除既有重複值

db.books.ensureIndex({ name: -1 }, { unique: true, dropDups: true })

注意:dropDups 會刪除重複文件,僅保留第一筆,資料將永久遺失,生產環境請謹慎使用(MongoDB 3.0+ 已移除此選項)。

六、Hint:強制指定查詢使用的索引

db.books.find({ name: "1book", number: 1 }).hint({ name: -1 })

指定的索引必須已存在,否則會報錯。通常用於查詢優化器選錯索引時的干預。

七、Explain:深入分析查詢執行計畫

db.books.find({ name: "1book" }).explain()

關鍵輸出欄位解讀

  • cursor:BtreeCursor name_1 表示使用了 name 欄位的 B-Tree 索引
  • nscanned:掃描的索引條目數
  • nscannedObjects:實際檢查的文件數
  • millis:查詢耗時(毫秒),0 代表極快
  • indexOnly:true 表示「覆蓋索引查詢」,無需讀取文件
  • indexBounds:索引掃描的具體範圍

八、索引管理操作

1. 查看所有索引

db.system.indexes.find()
db.system.namespaces.find()

2. 後台建立索引(避免鎖表)

db.books.ensureIndex({ number: 1 }, { background: true })

大型集合建索引會鎖定資料庫,background: true 允許建索引過程中繼續處理讀寫請求。

3. 刪除索引

// 精確刪除單一索引
db.runCommand({ dropIndexes: "books", index: "name_1" })

// 批量刪除所有非 _id 索引
db.runCommand({ dropIndexes: "books", index: "*" })

九、地理空間索引(2d 索引)

MongoDB 內建強大的地理空間查詢能力,支援平面幾何運算。

1. 準備測試資料

var map = [
  { gis: { x: 185, y: 150 } },
  { gis: { x: 70, y: 180 } },
  { gis: { x: 75, y: 180 } },
  { gis: { x: 185, y: 185 } },
  { gis: { x: 65, y: 185 } },
  { gis: { x: 50, y: 50 } },
  { gis: { x: 50, y: 50 } },   // 重複點
  { gis: { x: 60, y: 55 } },
  { gis: { x: 65, y: 80 } },
  { gis: { x: 55, y: 80 } },
  { gis: { x: 0, y: 0 } },
  { gis: { x: 0, y: 200 } },
  { gis: { x: 200, y: 0 } },
  { gis: { x: 200, y: 200 } }
]

for (var i = 0; i < map.length; i++) {
  db.map.insert(map[i])
}

2. 建立 2d 索引並自訂座標範圍

db.map.ensureIndex({ "gis": "2d" }, { min: -1, max: 201 })

3. 常用空間查詢範例

① 找出距離 (70,180) 最近的 3 個點

db.map.find(
  { gis: { $near: [70, 180] } },
  { gis: 1, _id: 0 }
).limit(3)

② 查詢矩形區域內的所有點

var box = [[50, 50], [190, 190]]  // 對角線兩點
db.map.find(
  { gis: { $within: { $box: box } } },
  { gis: 1, _id: 0 }
)

③ 查詢圓形區域內的點

var center = [55, 80]
var radius = 50
db.map.find(
  { gis: { $within: { $center: [center, radius] } } }
)

總結

索引是 MongoDB 效能調優的核心工具。合理規劃單欄位、複合、唯一、地理空間等各類索引,並善用 explain() 分析執行計畫、hint() 干預優化器、background 選項避免鎖表,能讓查詢效能提升數個數量級。記住:索引雖好,切勿過度,需在讀寫比例、記憶體佔用、維護成本間取得平衡。

copyright © 萬盛學電腦網 all rights reserved