創建文檔所在位置的查找清單, 使用索引能夠快速查找, 減小遍歷次數, 提升查找效率數組
即: 什麼狀況下不適合創建索引?spa
索引自己也佔據空間, 數據量很小的時候就不必用索引code
索引表會根據數據的修改及時變動, 過於頻繁的變動也會對數據增刪改的效率形成較低blog
所以大量增刪改的時候 查詢需求量不大 ,不須要建立索引索引
命令文檔
db.collection.createIndex()
db.collection.ensureIndex()
db.collection.createIndexes()
功能 建立索引get
參數 索引域 選取要被建立所用的域, 字典形式域名
取值 {域名:1/-1} 1 正向索引, -1 逆向索引io
索引選項class
一般來加名字, 雖然不設置默認也會自動添加名字 以 域名_1/-1 的形式自動建立
也能夠指定 索引類型 默認是普通索引
其餘類型往下看其餘索引部分
ps:
ensureIndex 和 createIndex 沒啥差異,只是名字不同而已.
ensureIndex 目前也不被官網更新註明, 後期可能會被抹除
更推薦 createIndex, 更親和也更被承認
createIndexes([{},{}]) 建立多個索引, 不必, 索引通常都是建立不多就夠了
爲 name 域 建立正向索引
> db.class.createIndex({name:1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
經過第二個參數定義索引名稱 爲 Age
爲 age 字段 建立正向索引, 且設置名字爲 Age
> db.class.createIndex({age:1},{name:"Age"}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 3, "ok" : 1 } >
命令
db.class.getIndexes()
功能 查看索引詳細
參數 無參數
返回結果
當前集合中的全部索引
默認 _id 域是由系統自動建立的, 且該索引不能被刪除
1 表示正向索引
-1 表示逆向索引
> db.class.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "grade.class" }, { "v" : 2, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "grade.class" } ] >
命令
db.collection.dropIndex()
功能 刪除一個除了 _id 之外的索引
參數 索引名稱 ( 設置的 name ) / 鍵值對
實例
> db.class.dropIndex("Age") { "nIndexesWas" : 3, "ok" : 1 } > db.class.dropIndex({"name":1}) { "nIndexesWas" : 2, "ok" : 1 } >
刪除全部除了 _id 之外的索引
db.collection.dropIndexes()
根據多個域建立一個索引
db.class.createIndex({name:1,age:-1},{name:"name_age"})
若是某個域建立索引, 該域的值是子文檔 / 數組 , 則對子文檔或者數組的某項查詢也是索引查詢
ps:
此索引並不須要你專門作什麼操做, 只是一種行爲定義
當你給 book :{xx:"xx"} , book 域建立索引
則 進行 "book.xx" 的查找的時候則爲 子文檔索引查找
要求建立索引的域不能有重複值
db.class.createIndex({name:1},{unique:true})
若是建立索引時,某些文檔不存在指定索引域,則忽略這些文檔
db.class.createIndex({age:1},{sparse:true})