索引是資料庫查詢效能的關鍵。當系統執行查詢時,若缺乏適當索引,MongoDB 必須掃描集合中的每一份文件(全集合掃描),這在大量資料下會嚴重拖慢效能。建立索引後,查詢優化器可透過 B-Tree 結構快速定位文件,實現數量級的效能提升。
for (var i = 0; i < 200000; i++) {
db.books.insert({ number: i, name: i + "book" })
}
var start = new Date()
db.books.find({ number: 65871 })
var end = new Date()
print(end - start) // 通常需數十至上百毫秒
db.books.ensureIndex({ number: 1 })
同樣查詢耗時將降至 0-1 毫秒,效能提升顯著。
1 為升序,-1 為降序;單欄位索引方向對單向查詢影響不大,但複合索引與排序操作時須謹慎規劃。db.books.ensureIndex({ name: -1 }, { name: "bookname" })
自訂名稱便於後續管理與識別。
db.books.ensureIndex({ name: -1 }, { unique: true })
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+ 已移除此選項)。
db.books.find({ name: "1book", number: 1 }).hint({ name: -1 })
指定的索引必須已存在,否則會報錯。通常用於查詢優化器選錯索引時的干預。
db.books.find({ name: "1book" }).explain()
cursor:BtreeCursor name_1 表示使用了 name 欄位的 B-Tree 索引nscanned:掃描的索引條目數nscannedObjects:實際檢查的文件數millis:查詢耗時(毫秒),0 代表極快indexOnly:true 表示「覆蓋索引查詢」,無需讀取文件indexBounds:索引掃描的具體範圍db.system.indexes.find()
db.system.namespaces.find()
db.books.ensureIndex({ number: 1 }, { background: true })
大型集合建索引會鎖定資料庫,background: true 允許建索引過程中繼續處理讀寫請求。
// 精確刪除單一索引
db.runCommand({ dropIndexes: "books", index: "name_1" })
// 批量刪除所有非 _id 索引
db.runCommand({ dropIndexes: "books", index: "*" })
MongoDB 內建強大的地理空間查詢能力,支援平面幾何運算。
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])
}
db.map.ensureIndex({ "gis": "2d" }, { min: -1, max: 201 })
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 選項避免鎖表,能讓查詢效能提升數個數量級。記住:索引雖好,切勿過度,需在讀寫比例、記憶體佔用、維護成本間取得平衡。