MongoDB中的索引操作
索引的管理
1 創(chuàng)建索引
db.集合名詞.ensureIndex(<keys>,<options>);
db.requestLog.ensureIndex({'createTime':-1});
options:創(chuàng)建索引時(shí)刻定義的索引參數(shù),可選參數(shù)如下:
| Parameter | Type | Description |
| backgroud | Boolean | 建索引過程阻塞其他數(shù)據(jù)庫操作,默認(rèn)為fasle, 當(dāng)集合數(shù)據(jù)量大時(shí),創(chuàng)建索引需要大量的時(shí)間 |
| unique | Boolean | 建立的索引是否唯一,默認(rèn)為false, 指定為true創(chuàng)建唯一索引 |
| expireAfterSeconds | Integer | 指定一個(gè)以秒為單位的數(shù)據(jù),完成TTL設(shè)定,設(shè)定集合的生存時(shí)間 |
| name | String | 索引的名稱 |
2 查看索引
db.集合名.getIndexes();
// 查看集合的key
db.集合名.getIndexKey();
// 查看索引詳情
db.集合名.getIndexSpecs();
// 查看索引大小,is_detail可選,可傳0,1,true,false
db.集合名.totalIndexSize(is_detail);
// 重建索引,可減少索引存儲(chǔ)空間,減少索引碎片,優(yōu)化索引查詢效率,
// 一般在數(shù)據(jù)大量變化后,會(huì)使用重建索引來提升索引性能,重建索引是刪除原索引重新創(chuàng)建的過程,不建議反復(fù)使用
db.集合名.reIndex();
3 刪除索引
db.集合名.dropIndex( '索引名' )
// 刪除所有的自建索引
db.集合名.dropIndexes();
4 索引的額外屬性
4.1 唯一索引(unique index)
db.student.creatIndex( { 'name':1 }, { 'unique': true } );
4.2 ttl索引
可以針對(duì)某個(gè)時(shí)間字段,指定文檔的過期時(shí)間
db.stu.ensureIndex( {'birth':1} , {'expireAfterSeconds': 3} ) ;
ttl索引不保證在到期后立即刪除過期數(shù)據(jù)。
文檔的到期時(shí)間與mongodb從數(shù)據(jù)庫中刪除文檔的時(shí)間之間可能存在延遲。
刪除過期文檔的后臺(tái)任務(wù)每60秒運(yùn)行一次,文檔可能在文檔到期和后臺(tái)運(yùn)行之間的期間保留在集合中。
TTL索引不能作為即時(shí)數(shù)據(jù)過期依據(jù)。
4.3 部分索引 (partial index)
db.stu.createIndex( {'name':1}, { 'particalFilterExpression': {‘a(chǎn)ge’ : {$gt: 25} } }) ;

浙公網(wǎng)安備 33010602011771號(hào)