MongoDb索引
Mongo 索引
語法:db.collection.ensureIndex({filed:1});
注:1.預設是曾序索引
2.預設索引是用btree組織
說明:1代表asc升序索引 -1 降序
子文件建立索引:
db.collection.ensureIndex({'fleld.subfiled':1});
說明: 為collection中文件的filed域下的subfiled域建索引
例: db.user.insert({userid:1,email:'[email protected]',intro:{height:175,age:24}}
db.user.ensoueIndex({'intro.height':1,'intro.age':1});
說明:此例為user表下的intro欄位中的height,age欄位建索引
多列建立索引:
db.collection.ensureIndex({field:1/-1},{unique:true});
說明: 1:field列上設定唯一索引 2:也可以針對"多列"設定唯一索引
例: db.user.ensureIndex({userid:1},{unique:true});
db.user.ensureIndex({a:1,b:1},{unique:true});
稀疏索引建立
db.collection.ensureIndex({field:1/-1},{sparse:true});
說明:稀疏索引是指--只針對含有field列的document建索引 而不指定此項,則不含field列的文件,把field的值理解為null,再建索引
例: db.user.ensureIndex({school:1},{sparse:true});
db.user.find({school:null});
雜湊索引建立
db.collection.ensureIndex({field:'hashed'});
說明: 1. 可以單個欄位或子文字欄位上建立hash索引
2. 不可以針對"多個列"建立hash索引 例: db.collection.ensureIndex('intro.height':'hashed');
檢視已有索引
db.collection.getIndexes();
刪除指定索引:
db.collections.dropIndex({filed:1/-1/'hashed'});
例: db.user.dropIndex({'intro.height':'hashed'});
刪除所有索引:
db.collection.dropIndexes();
注:_id列的索引不會被刪除
重建索引
db.collection.reIndex()
作用: 重建collection中的所有索引,包括_id 意義: 減少索引檔案碎片
例: db.user.reIndex()