1. 索引的创建(创建索引:db.collections.ensureIndex({...})
mongodb采用ensureIndex来创建索引,如:
db.user.ensureIndex({"name":1}) #name字段上创建索引,升序,倒序为-1
表示在user集合的name键创建一个索引,这里的1表示索引创建的方向,可以取值为1和-1
在这里面,我们没有给索引取名字,mongodb会为我们取一个默认的名字,规则为keyname1_dir1_keyname2_dir2...keynameN_dirN
keyname表示键名,dir表示索引的方向,例如,上面的例子我们创建的索引名字就是name_1
索引还可以创建在多个键上,也就是联合索引,如:
> db.user.ensureIndex({"name":1,"age":1})
这样就创建了name和age的联合索引
2、查看/显示集合的索引:db.collectionName.getIndexes()或则db.system.indexes.find()
3、删除索引
db.abc.getIndexes() #查看索引
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.abc"
},
{
"v" : 1,
"key" : { #索引字段
"a" : "hashed"
},
"name" : "a_hashed", #索引名
"ns" : "test.abc"
},
{
"v" : 1,
"key" : {
"b" : 1
},
"name" : "b_1",
"ns" : "test.abc"
},
{
"v" : 1,
"key" : {
"c" : 1
},
"name" : "idx_c",
"ns" : "test.abc"
}
]
zjy:PRIMARY> db.abc.dropIndex({"a" : "hashed"}) #删除索引,指定"key"
{ "nIndexesWas" : 4, "ok" : 1 }
zjy:PRIMARY> db.abc.dropIndex({"b" : 1}) #删除索引,指定"key"
{ "nIndexesWas" : 3, "ok" : 1 }
zjy:PRIMARY> db.abc.dropIndex("idx_c") #删除索引,指定"name"
{ "nIndexesWas" : 2, "ok" : 1 }
zjy:PRIMARY> db.abc.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.abc"
}
]
zjy:PRIMARY> db.abc.dropIndex("*") #删除索引,删除集合的全部索引
{
"nIndexesWas" : 4,
"msg" : "non-_id indexes dropped for collection",
"ok" : 1
}
4)重建索引:索引出现损坏需要重建。reindex
zjy:PRIMARY> db.abc.reIndex() #执行
{
"nIndexesWas" : 1,
"nIndexes" : 1,
"indexes" : [
{
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "test.abc"
}
],
"ok" : 1
}
5)强制使用指定索引。hint
db.abc.find({"c":1,"b":2}).hint("b_1") #hint里面是"索引字段"或则"索引名"