對單一鍵建立索引
db.collection.createindex( {name: 1} )
在集合的同一個鍵上不能重複建立單一索引;若已經建立了索引,再在間一個Key 上建立索引,將給予出錯提示。
1升序,-1降序
嵌套文檔單字段索引
db.books.insert( { name:" <dirty cocks故事》", price: 30 , tags: {press: "飛出版社" , call :"1820000000"} } ) db.books.createIndex({"tags.press" :1})
唯一索引
db.collection.createindex( {name: 1}, {unique: true} //(注意MongoDB的命令是大小寫敏感的) )
name的值必須是唯一的,不能有重複值出現;否則,MongoDB將新插入的重複文檔予以拒絕。在沒有指定{unique:true}參數選項的情況下,索引方法允許存在宇段值重複的多文檔記錄。
建立多字段索引(組合/複合索引)
//對兩個字段建立索引 db.books.createindex( { price:l , color:-1 } ) //用sort 排序查詢 db.books.find({}, {_id: 0}).sort.({price: 1, color: -1})
上述代碼先用createIndex命令建立price、color多鍵組合索引,然後用find()查找文檔記錄;對查找出來的文檔記錄結果用sort({price: 1, color: -1}先用做price 升序排序,在price價格一樣的情況下,再對price相同記錄做color降序排序
多宇段唯一索引
db.books.createindex({name: l , price: l}, {unique: true}) //是允許的
只要name 和price 組合起來的值保持唯一性
基本文本索引
db.books.createindex({narne: "text"}) //爲name 建立文本索引
指定權重文本索引
db.books.createIndex( { name: "text", price: "text" }, { weights: {name: 10}, //爲name指定索引權重 name: "TextIndex" //默認情況下,price權重爲1 } );
通配符文本索引
爲指定集合中的所有字符串內容進行搜索提供通配索引,這在高度非結構化的文檔裏比較有用
db.books.createIndex({"$**": "text"})
哈希索引
用於支持對分片鍵(帶哈希鍵值對的分片集合)的分片數據索引,主要用於分佈式數據索引
db.collection_name.createIndex({_id: "hashed"})
命令說明:key爲含有哈希值的鍵
(1.hashed 索引不支持多字段索。2.hashed會把浮點數的小數部分自動去掉,所以對浮點數字段進行索引時,要注意該特殊情況。3.hashed 不支持唯一索引)
還可以用ensureIndex()創建索引
>db.collection.ensureIndex({id: "hashed"})
MongoDB 3.0開始用createindex 命令代替ensureIndex
(1)db.collection.droplndex(index):移除集合指定的索引功能。index參數爲指定需要刪除的集合索引名,可用getlndexes()函數獲取集合的所有索引名稱。
(2)db.collection.droplndexes():移除一個集合的所有索引功能。
(3)db.collection.getlndexes():返回一個指定集合的現有索引描述信息的文檔數組。
(4)db.collection.relndex():刪除指定集合上所有索引,並重新構建所有現有索引。在具有大量數據集合的情況下,該操作將大量消耗服務器的運行資源,引起運行性能急劇下降等問題的發生。
(5)db.collection.totallndexSize():提供指定集合索引大小的報告信息。